Saturday, December 15, 2012

Threading in Detail



Thread
• Thread is light weight where as a process is heavy weight.
• A thread is a part of the program. But a process is a program itself
• Programmatically introduced or as result of programming model
• Managed object within the CLR

Multithreading
• Multi-threading is used
– To take advantage of multi-processor systems while doing intensive
computation
– Separate threads can be created to perform different tasks such as
• Keeping the user interface "live"
• Waiting for I/O
• Split out complex test conditions and loops
• The CLR provides in built support for writing multithreaded code.
Priority
– Values for this property are from the ThreadPriority enumeration
– The values are
• Highest _ AboveNormal
• Normal _ BelowNormal
• Lowest
ThreadState
– Used to determine current state of a thread
– Returns a ThreadState enumeration member
– Members of the ThreadState enumeration
• Unstarted _ Running
• WaitSleepJoin _ Suspended
• SuspendRequested _ AbortRequested
• Stopped

Thread Methods
Method                         Action
Start                    Causes a thread to start running.
Sleep                   Pauses a thread for a specified time.
Suspend              Pauses a thread when it reaches a safe point.
Abort                   Stops a thread when it reaches a safe point.
Resume              Restarts a suspended thread

Join                     Causes the current thread to wait for another thread to finish. If used with a timeout value, this method returns True if the thread finishes in the allotted time.
Interrupt            Interrupts a thread that is in the WaitSleepJoin thread state.

Creating a thread
• Thread Class
• Represents a thread
• Present in System.Threading class
• Instantiates a thread

Syntax:
Thread myThread = new Thread (entryPoint);
• ThreadStart Delegate
• It is a built-in delegate used in creating threads
• It points to the function that initiates the thread
• Signature:
public delegate void ThreadStart();
• Common access from all language variants
Initializing Threads
• Threads are explicitly created using Thread class
• They are explicitly scheduled using the Timer class from the namespace:
System.Threading
• The work items are queued for execution by:
System.Threading.ThreadPool
• To create a new thread, a new Thread object is created , as shown in the
following code:
using System.Threading;
...
ThreadStart ts = new ThreadStart(myMethod);
Thread p1 = new Thread(ts);
p1.Name = "MyThread";
p1.Start();

Multithreading scenario


Working with threads

• After an object of the Thread class has been created, the Start method is
called to make it to begin executing,
– myThread.Start();
• The thread is now scheduled to run by the operating system and will continue
to execute until it exits its ThreadStart method or until the thread is forced to
stop by some other means.
• To stop the execution of a thread, its Suspend method is called:
– myThread.Suspend();
• The current state of a thread can be determined through the ThreadState
property,
– Thread myThread = Thread.ThreadState;
Why use Threads?
• Process tasks without user interaction
• Avoid blocking UI elements
• Optimize applications for multi-processor systems
• Juggle data preparation with data presentation

Disadvantages of Threads
• Tasks requiring identical resources
– Example: Multi-threaded file IO
• Excessive thread usage
– Context switching can degrade performance
• On single processor machines
– If multiple threads don’t synchronize their access of shared data, the
data will become corrupted.
• On multiple-processor system
– several threads can execute at exactly the same time. If these threads
attempt to simultaneously change the value of a variable, the results are
unpredictable.

Synchronization
• One of the crucial aspects of working with threads
• Only one thread should get access to resources at any one time.
• Essential when multiple threads access shared objects.
• Need to Identify critical regions that access resources
• All objects have a lock that can be obtained
– Only one thread can get the lock at one time
– Other threads get blocked and have to wait
• The locks have to be released otherwise deadlock can result
Thread Synchronization
• Multiple threads contend for resources such as
– Instance variables
– Database connections
– GUI controls
• Writing creates more problems than reading

Thread Pools
• Set of "worker" threads
• Thread controller assigns them to tasks
• Submit task to thread controller
• Number of threads in pool can grow or shrink
– Thread controller can use common metrics
– Developer does not have to worry about starting and terminating threads
• Useful for optimizing thread usage where there are many clients or units of
Work
• ThreadPool class
– QueueUserWorkItem static method
• Work item consists of
– Method to run is defined by WaitCallback delegate (public void (object state))
– State to be passed as object
• Still pass other state by setting variables on the method's object
• Need synchronization as before
• Events work well in this environment
• To use a .NET Event
– Define a callback method
– Register with event producer
– Event producer then notifies all listeners
• Timed execution of delegates
• Useful for timer events etc.
• Use RegisterWaitForSingleObject

No comments:

Post a Comment