Monday, November 1, 2010

Synchronization Primitives

1. Simple blocking : Sleep, Join, and Task.Wait are simple blocking methods. These mechanisms waits until another thread to finish or period of time to elapse.

2. Locking :  The standard exclusive locking constructs are lock (Monitor.Enter/Monitor.Exit),Mutex, and Spinlock . The nonexclusive locking constructs are semaphore and the reader/writer locks.

3. Signaling : There are two commonly used signaling devices: Event wait handlers and Monitor’s Wait/Pulse methods.

4. Nonblocking synchronization constructs : C# provide the following nonblocking constructs: Thread.Memorybarrier,Thread.VolatileWrit and the InterLocked class.


Lock :

           lock ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread attempts to enter a locked code, it will wait, block, until the object is released. Using lock keyword only one thread can access section of code at a time and once it finishes then only another thread in a queue will be accessed.

Syntax of lock keyword :

Object lockObj= new Object();
lock (lockObj)
    // code section
Lock calls Enter at the beginning of the block and Exit at the end of the block.

DO's and DONT's :

* Avoid locking on public types.
* Avoid locking on instances which is not in your code control.
* Better to lock on private objects
* Lock on private static object variable to protect data common to all instances.
Monitor :
       Monitor class also works same as lock in which it provides a mechanism that synchronizes access to objects.But it uses The Enter method allows one and only one thread to proceed into the following statements; all other threads are blocked until the executing thread calls Exit. It Monitor is unbound, which means it can be called directly from any context. This class is under System.Threading namespace.

Code snippet shows Monitor class:

Object lockObj= new Object();


      A mutex is similar to a monitor; it prevents the simultaneous execution of a block of code by more than one thread at a time.Unlike monitors, however, a mutex can be used to synchronize threads across processes.It represents by the mutex class.

Click here to Download Softwares