1. When you have multiple threads accessing a shared resource in such a way that the resource does not become corrupt
2. When one thread needs to notify one or more other threads that a specific task has been completed
User Mode
1. Interlocked Methods
a. These methods are extremely fast and easy to use.
b. The System.Threading.Interlocked class defines a bunch of static methods that can atomically modify a variable in a thread-safe way.
public static class Interlocked {
// Atomically performs (location++)
public static Int32 Increment(ref Int32 location);
// Atomically performs (location--)
public static Int32 Decrement(ref Int32 location);
// Atomically performs (location1 += value)
// Note: value can be a negative number allowing subtraction
public static Int32 Add(ref Int32 location1, Int32 value);
// Atomically performs (location1 = value)
public static Int32 Exchange(ref Int32 location1, Int32 value);
// Atomically performs the following:
// if (location1 == comparand) location1 = value
public static Int32 CompareExchange(ref Int32 location1,
Int32 value, Int32 comparand);
}
2. Critical Sections
A critical section is a small section of code that requires exclusive access to some shared resource before the code can execute.
Implemented in .NET using the Monitor class.
private void SomeMethod() {
lock (this) {
// Access object here...
}
}
private void SomeMethod() {
Object temp = this;
Monitor.Enter(temp);
try {
// Access object here...
}
finally {
Monitor.Exit(temp);
}
}
3. ReaderWriterLock
There is a very common thread synchronization problem known as the multiple-reader/
single-writer problem.
a. When one thread is writing to the data, no other thread can write to the data.
b. When one thread is writing to the data, no other thread can read from the data.
c. When one thread is reading from the data, no other thread can write to the data.
d. When one thread is reading from the data, other threads can also read from the data.
Should never ever use the class.
Note : Monitor and ReaderWriterLock methods allow synchronization of threads running
only in a single AppDomain.
Kernel Mode
1. Kernel objects can be used to synchronize threads that are running in different AppDomains or in different processes.
2. Whenever a thread waits on a kernel object, the thread must always transition from user mode to kernel mode (1000 CPU cycles), causing the thread to incur a performance hit.
3. WaitHandle class is a simple class whose sole purpose is to wrap a Windows kernel object.