Let's think your application (process) is a project manager
and each thread of it as a project team member. You surely want your team
members to work together, not independently, right? For this you would want
them to instruct and manage based on guidelines, work approach, periodic status
reporting, team communication, proper resource utilization, conflict prevention,
etc. You would want to have total control over the work environment to get the
final target to accomplish. So here you need to have synchronization among team
members. In the same way, we need synchronization among threads.
Important constructs which we can use for
Synchronization
Some important objects which we can use for Synchronization
are given below. We will see uses of all these in later part of the article.
1.
To block current thread
·
Sleep() - This is used very commonly to
block thread for some specified time interval (in milliseconds)
·
Join() - To block current thread and
instantiate another thread. When new thread finishes, it will resume its
processing.
2.
To implement code locking mechanism among
threads
·
SyncLock - To lock some part of
code to be run by only one thread at a time. SyncLock
term is used in VB.Net. Its C# equivalent is Lock.
·
Monitor - Similar to mutex in the
functionality but different coding approach with extra implementation features.
·
Mutex - To lock some part of code to be
run by only one thread at a time with cross-process accessibility feature.
Mutex is the extension of windows kernel objects.
·
Semaphore - To lock some part of code to
be run by only one thread at a time with cross-process accessibility feature,
with additional feature to prevent deadlock in better way. Semaphore is the
extension of kernel objects.
·
Synchronization Context - To lock some
part of code to be run by only one thread at a time just by using class
attribute [Synchronization] and inheriting ContextBoundObject class.
·
ReaderWriteLock - To allow specific
number of threads to run particular set of code simultaneously with some access
privilege set among them.
3.
To implement event-driven thread synchronization
in the application
·
EventWaitHandle - A class which provides
some methods and properties to manage threads by sending/receiving event signal
among each other. This also uses windows kernel object internally to perform
the task. Two important class which we use are:
·
1. AutoResetEvent
·
2. ManualResetEvent
I will describe the implementation procedures of each one
right from here. It will continue in my next few articles as well.