Tuesday, August 9, 2016

Threat Safe

Threads are lightweight processes
Normally programs where a single thread runs as a single process which is the running instance of the application. 


1)Semaphore Class

  • Limits the number of threads that can access a resource or pool of resources concurrently.
  • Semaphore is advance version of mutex with additional features. 
  • Work with Internal or External threads
  • Threads enter the semaphore by calling the WaitOne method, and release the semaphore by calling the Release method.
  • The count on a semaphore is decrease each time a thread enters the semaphore, and incremented when a thread releases the semaphore. When the count is zero, subsequent requests block until other threads release the semaphore.When all threads have released the semaphore, the count is at the maximum value specified when the semaphore was created.
  • A thread can enter the semaphore multiple times, by calling the WaitOne method repeatedly. 
  • To release some or all of these entries, the thread can call the parameterless Release() method overload multiple times, or it can call the Release(Int32) method overload that specifies the number of entries to be released, Relase() same as Release(1)
  • SemaphoreFullException is thrown when full.
  • All will stop at WaitOne(), waitOne() bellow code will not be run when the semaphore is full , it run when someone call Release().
  • There is no guaranteed order, such as FIFO or LIFO.
2)Lock/Monitor
  • Only 1 thread enter. If another thread tries to enter a locked code, it will wait, block, until the object is released. (internal thread - within application itself)
  • Best practice is to define a private object to lock on, or a private static object variable to protect data common to all instances.
  • You can't use the await keyword in the body of a lock statement.(private Object thisLock = new Object();)
3)Mutex
Mutex ensures the thread safety which are out process that is threads (Only One Thread) which
coming from outside of an application (External threads). 

4)SemaphoreSlim

SemaphoreSlim is an advance version of Monitor. SemaphoreSlim ensures the thread safety with internal threads but between scope of SemaphoreSlim it allows us to pass one or more threads to pass and executes their task. SemaphoreSlim also provides you an advance limit where you can limit the number of threads for an execution.

Lock vs SemaphoreSlim

Both is internal threads, Lock only 1 entry and semaphoreSlim can limit numbers of entry
Different Lock and Mutex
lock is specific to the AppDomain, while Mutex to the Operating System allowing you to perform cross-process locking and synchronization.


Different Mutex and Semaphore 
Both is external threads, Mutex only 1 entry and Semaphore can limit numbers of entry.


Only One
More Than One
Internal Thread
Lock/Monitor
SemaphoreSlim
External Thread
Mutex
Semaphore

No comments:

Post a Comment