THREAD SYNCHRONISATION
TECHNIQUES
Thread
Thread States
Lock
It ensures only one thread to be executed in given moment of time.
The lock keyword marks a statement block as a critical section by obtaining the mutual-
exclusion lock for a given object, executing a. statement and then releasing the lock
Monitor
Lock keyword is just a short-form of Monitor.
The Monitor class has the following methods for the synchronize access to a region of code by taking and
releasing a lock:
Monitor.Enter
Monitor.TryEnter
Monitor.Exit.
var lockObj = new Object();
if (Monitor.TryEnter(lockObj)) {
try {
// The critical section.
}
finally {
// Ensure that the lock is released.
Monitor.Exit(lockObj);
}
}
else {
// The lock was not axquired.
}
Mutex
Mutex provides safety against the external threads.
Semaphore
Semaphore allows one or more threads to enter to executes their task with thread safety.
Summary
Threadings Uses and Misuses
Maintaining a responsive user interface.
Making efficient use of an otherwise blocked CPU.
Parallel programming.
Allowing requests to be processed simultaneously.
Disadvantages:
Interaction between threads add complexity
Creation / tear down cost.
To be continued..
SemaphoreSlim
ReaderWriter locks
Interlocked class
SpinLocks
Deadlocks