14 f08 Multithreading
14 f08 Multithreading
A Process
• A Process is a running application
• A Process is composed of Threads
– e.g. a process may have:
• A GUI thread
• Several computational threads
• A file I/O thread
• A print thread
1
Multithreading
•Thread
–The fundamental unit of execution to which processor
allocates processor time
•A dispatchable unit of code
–Threads run concurrently and share the cpu(s)
•OS manages running threads with scheduling algorithms
•Switches processor time between threads
•Done so fast and efficiently that it appears all threads are
running simultaneously
–A .NET managed application begins as a single thread
•Can spawn additional threads to partition its tasks
–On multi-cpu system, applications can run faster since
different threads can run on different processors
Asynchronous Execution
•Threads run asynchronously with respect to each
other
–So independent units of work can be performed in parallel
•Example: a GUI application that enters into a long
computational loop
–Running as a single thread:
•While application’s single thread is computing, messages on the
message queue are ignored
–So the application’s user interface is frozen until computation finishes
2
Multithreading Complexities
•Multithreaded applications are hard to write & debug
•Parallelism of concurrently running threads adds an
extra layer of complexity
–e.g., threads to write then read a data structure
•If both are in a single thread, we know write will occur first
•But if in separate threads, we don’t know in advance when each
thread is going to run
–Read first then write ? old (wrong) data will be read
•Threads need to be synchronized
–Also bugs are dependent on timing
•Very difficult to reproduce
•It’s almost impossible to be sure that a multithreaded program
is free of bugs
Threads in .NET
3
Some Thread Class Properties
•bool IsBackground
–false (default) means thread runs in foreground
–An application doesn’t end until all its foreground threads have finished
•string Name
–Retrieve/change a thread’s name
•Thread CurrentThread
–Static property returning a reference to the calling thread
–Use result to get or change properties of a thread
•ThreadPriority Priority
–ThreadPriority is an enumeration:
•Highest, AboveNormal, Normal (default), BelowNormal, Lowest
–Determines relative amount of processor time allotted to the thread
–Can be changed:
Thread myThread = Thread.CurrentThread;
myThread.Priority = ThreadPriority.AboveNormal;
•bool IsAlive
Starting Threads
•Instantiate a Thread object
–Give constructor a new “thread method”
•This is the method the thread executes when it starts
•Must be “wrapped” in the ThreadStart delegate
•Then use the thread’s Start( ) method
•Example:
Thread myThread = new Thread (new ThreadStart (myThreadMethod) );
myThread.Start();
•Starts the thread and causes myThreadMethod( ) to run
•Your application must implement this method:
void myThreadMethod( ) { // code to run };
–Thread is now “alive” and remains alive until it terminates
–When the “thread method” returns, the thread ends
4
Threads-One & Threads-Two
Example Programs
• Form has “Toggle Background Color” & “Start Computation”
buttons and a label
– First button handler toggles background between red and green
– Second button handler starts a long, nested-loop computation
• When computation is done, label control is turned blue and displays an “All
Done” message
• Running as a single thread (as usual):
– After “Start Computation” button is clicked
• Program does not respond to “Toggle Background Color” button until
computation is done (seems to be dead)
• Running in two threads:
– Foreground thread starts a background thread to do the computation when
user clicks the “Start Computation” button
– Now the program responds to the “Change Background Color” button
while the computation is being done
5
Terminating a Thread
•Abort( ) method terminates a running thread
myThread.Abort(); //terminates myThread
–Always works for managed thread, but may not
if the application contains unmanaged code
•Many times a thread should pause until the
thread it is trying to abort terminates
–Join( ) method does that
otherThread.Abort( ); // ask the other thread to finish
otherThread.Join( ); // “joins” the other thread
•pauses until other thread finishes
6
Starting Processes on the System
•A Process component provides access to processes that are
running or can run on the system
–In System.Diagnostics namespace
•To run a process:
–Instantiate a new Process object
–Set its StartInfo.FileName property to the name of the
executable file
–Invoke its Start( ) method
Process myProc = new Process( );
myProc.StartInfo.FileName = “c:\\Windows\\Notepad.exe”;
myProc.Start( );
•StartProcess example program
–Allows user to start any application program on the system