Monday, 5 March 2018

030 C# Multithreading

Multithreading :
A thread is a path  of program execution. A program can run in a thread without interfering the other program. Thread run separately and used for multitasking. Thread is a lightweight process and each thread  have a unique flow . In the older days when multitasking concept was not present, a program run with procedural approach, threading was not relevant, but now it is indispensable computer is doing multitasking, end user do several job at a time. You have open a word document and do printing job the in the same computer .Thread is created corresponding the process and do the job according to the priority.

Multitasking have two separate parts, process based,  thread based.

Process base : Process base execute program concurrently ,for example I am working with Word and  Excel. A complete program which is executing  is called process. Process do multitasking and multiple program concurrently.

               Thread is a unit of executable code or thread is  executive  quote for specific purpose. each process have one or more thread. A process can generate multiple thread also. For example I am doing dieting and printing both online notepad. The process generating printing job.

            The main advantage of thread is to optimize CPU usage. Use CPU idle time and thread priority can be set to do a job on priority higher or lower basis.Tread  comes under the namespace System.Tread.

Thread  have several States
  • Running  : A Thread has started and it is working not blocked or terminated.
  • Suspended : A Thread has requested to suspend until resume.
  • Block : A Thread enter a locked code , it will be blocked until the object is release.
  • Terminated: Kill a threat instantly.
  • Stopped : A Thread  has stopped working.
  • Resume : If a Thread has been suspended and it has been released from suspended state.

Thread are of  two type ,  foreground and background. A thread  is created is a foreground thread until we  force to run it as a background thread .Background thread automatically stop when all foreground thread  destroyed.

Threading comes under the namespace  System.Threading  .

Thread Class : It is a class under the normal namespace System.Threading. Thread class cannot be inherited. Thread class has several method and is inbuilt in it. Creating class do not start automatically, you need to invoke start method to start a thread. After a thread  has  started, you can resume stop sleep  comment depending upon the requirement.

Example 1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
     class Program
     {
          static void Main(string[] args)
          {

             Thread StudentThread = new Thread(new ThreadStart(AfterThreadEnd));
              StudentThread.Start();

          }

          private static void AfterThreadEnd()
         {
            Console.WriteLine("Tread Ended");
           Console.ReadKey();
        }
   }
}




 Here is some property of Thread
  
  • CurrentThread : Returns the instance of current thread.
  • IsAlive :Returns current thread alive or not .
  • IsBackground : get or set value current thread runs background or not.
  • Name : get or set the name of the current thread.
  • Priority :get or set the priority of the current thread.
  • ThreadState :Return a value corrosponding the thread state.

Example 1



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
       {
         static void Main(string[] args)
          {

                Thread StudentThread = new Thread(new ThreadStart(AfterThreadEnd));
                 StudentThread.Start();//Start The Thread
                 StudentThread.Name = "Student Thread";
                 Console.WriteLine(StudentThread.IsAlive);
                 Console.WriteLine(StudentThread.IsBackground);
                 Console.WriteLine(StudentThread.Name);
                 Console.WriteLine(StudentThread.Priority);
                 Console.WriteLine(StudentThread.ThreadState);
                Console.ReadKey();
           }
          private static void AfterThreadEnd()
          {
            Console.WriteLine("Tread Ended");
            Console.ReadKey();
         }
    }
}

Output




 Here are some inbuild method of Tread

  • Abort: terminate the thread
  • Interrupt:interrupt a thread which is in WaitSleepJoin state.
  • Join :block all the calling threads until this thread terminates.

  • Sleep(Int32):suspend the current thread for the specified milliseconds.
  • Start():Start a treat






Example of Sleep()


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
      class Program
       {
         static void Main(string[] args)
         {
               Student s = new Student();
               Thread StudentThread1 = new Thread(new ThreadStart(s.Thread1));
               StudentThread1.Start();//Start The Thread

                Thread StudentThread2 = new Thread(new ThreadStart(s.Thread2));
                 StudentThread2.Start();//Start The Thread
                 Console.ReadKey();

         }
     }
}

public class Student
{
              public void Thread1()
             {
                    for (int i = 0; i < 10; i++)
                     {
                     Console.WriteLine(i);
                     Thread.Sleep(200);
                      }
         }

             public void Thread2()
             {
                 for (int i = 0; i < 10; i++)
                  {
                   Console.WriteLine("Second Thread");
                  }
             }
}













 
ThreadPriority :There are five enumeration priority of a thread
1)ThreadPriority.Highest
2)ThreadPriority.AboveNormal
3)ThreadPriority.Normal
4)ThreadPriority.BelowNormal
5)ThreadPriority.Lowest

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
            class Program
            {
                static void Main(string[] args)
                 {
                        Student s = new Student();
                        Thread StudentThread1 = new Thread(new ThreadStart(s.Thread1));
                        StudentThread1.Start();//Start The Thread

                         Thread StudentThread2 = new Thread(new ThreadStart(s.Thread2));
                          StudentThread2.Start();//Start The Thread
                          StudentThread2.Priority = ThreadPriority.Highest;
                          Console.ReadKey();
                   }
         }
}

public class Student
{
           public void Thread1()
          {
              for (int i = 0; i < 10; i++)
               {
                 Console.WriteLine(i);
               }
          }
          public void Thread2()
          {
             for (int i = 0; i < 10; i++)
             {
              Console.WriteLine("Second Thread:"+i.ToString());
            }
        }
}





Thread Pulling 

Thread pulling is a background task and collection of several threads. A task is assign one or multiple threads which is running on background . Thread pulling is mainly server application and it is queue based. Thread pooling do not interfere with primary thread, primary thread is not affected by thread pulling. When a task is assign, the task is move to the queue  and wait for free threat, if any free trade is available, it is immediately assign to the task . If any free thread is not available, system wait for next thread  to be free. When it gets a free thread, immediately assign. In such a way, thread pulling reduce creating a new thread and reuse existing thread.Thus  it reduce the system overhead cost and time and CPU utilization.  

Thread pulling also comes under the namespace System.


using System.Threading;

Threading pulling is a class. Here is the example of thread pull class.  
System.Threading.ThreadPool


 Here is a example of how is it full can be used.
ThreadPool.QueueUserWorkItem(new WaitCallback(Run));

Below is the example of  thread pool. Example shows that, GetFeesMethod() method assign example1  to Thread pulll. When the  GetFeesMethod() method is completed, Thread is free, example1 execute using existing thread from thread pull.



using System;
using System.Threading;
using System.Collections.Generic;
using System.Diagnostics;

namespace ThreadPooling
{
       class Student
      {
         static void Main(string[] args)
         {
             GetFeesMethod();
             Console.ReadKey();
         }
        static void GetFeesMethod()
       {
          Console.WriteLine("GetFee Method Started");
           for (int i = 0; i <= 10; i++)
           {
            ThreadPool.QueueUserWorkItem(new WaitCallback(Example1));
          }
         Console.WriteLine("GetFee Method Ended");
      }
     static void Example1(object callback)
     {
               Console.WriteLine("Theread assigned to Example1");
                int l;
                for (int i = 0; i <= 10; i++)
               {
                l = i + 1;
              }
    }
  
}
}





Thread Synchronisation 

In multi threading system,thread  run separately without interfering each other. This is asynchronous process. But in some cases, several thread  want to access a shared resource like file ,variable  etc. Concurrent access to this resource thread  may conflict each other, then the system will go to deadlock, busy waiting stage. As thead using  the resource  and another thread also trying to access it. To avoid this Synchronisation concepts comes.  Synchronisation is a technique to run thread  smoothly, maybe they are trying to access the same resource . A thread  can be block, sleep, join, wait  state to implement Synchronisation. Synchronisation guarantee that one resource would be access by one thread at a time. If anther thread  trying to access the same resource, it have to wait  for the resource to be release by previous thread.


The example shows that, one thread is calling another thread. The first thread go to sleep condition and the second thread started. Thus Synchronisation handled.

using System;
using System.Threading;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System;
using System.Threading;

namespace CSharpThreadExample
{
             class Student
            {
                public static void Example1()
                   {
                       for (int i = 0; i < 5; i++)
                         {
                              Console.WriteLine(Thread.CurrentThread.Name + i);
                              Thread.Sleep(1000);

                               Thread t2 = new Thread(new ThreadStart(Example2));
                               t2.Name = "Child";
                               t2.Start();
                         }
                  }
              public static void Example2()
              {
              for (int i = 0; i < 5; i++)
                   {
                       Console.WriteLine("In thread " + Thread.CurrentThread.Name + i);
                      Thread.Sleep(1000);
                   }
             }

            static void Main(string[] args)
            {
               Thread t1 = new Thread(new ThreadStart(Example1));
               t1.Name = "Main";
               t1.Start();

              Console.ReadKey();
           }
      }
}



No comments:

Post a Comment

বাঙালির বেড়ানো সেরা চারটি ঠিকানা

  বাঙালি মানে ঘোড়া পাগল | দু একদিন ছুটি পেলো মানে বাঙালি চলল ঘুরতে | সে সমুদ্রই হোক , পাহাড়ি হোক বা নদী হোক। বাঙালির ...