- Add
- Increment
- Decrement
- Read
- Exchange (for setting the variable to a particular value)
- CompareExchange (for comparing two values and performing an operation based on the result)
Here's an example:
// Using the Interlocked class
namespace ThreadingInDotNet
{
class Program
{
static void Main(string[] args)
{
ThreadSafeType tst = new ThreadSafeType();
Thread th;
for (int i = 0; i < 20; i++)
{
th = new Thread(new ThreadStart(tst.PrintThreadId));
th.Start();
Thread.Sleep(1000);
}
}
}
class ThreadSafeType
{
int allowed = 1; // 1 means allowed, 0 means not
public void PrintThreadId()
{
if (Interlocked.Exchange(ref allowed, 0)==1)
{
Console.WriteLine("\n Thread ID:{0} acquired the lock,"
Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(3000);
Console.WriteLine(" Thread ID:{0} exiting lock,"
Thread.CurrentThread.ManagedThreadId);
Interlocked.Exchange(ref allowed, 1);
}
else
{
Console.WriteLine(" Thread ID:{0} was denied the lock,"
Thread.CurrentThread.ManagedThreadId);
}
}
}
}
You can see the output of the program below:
Thread ID:3 acquired the lock
Thread ID:4 was denied the lock
Thread ID:5 was denied the lock
Thread ID:6 was denied the lock
Thread ID:3 exiting lock
Thread ID:7 acquired the lock
Thread ID:8 was denied the lock
Thread ID:9 was denied the lock
Thread ID:7 exiting lock
Thread ID:10 acquired the lock
Thread ID:11 was denied the lock
Thread ID:12 was denied the lock
Thread ID:10 exiting lock
Thread ID:13 acquired the lock
Thread ID:14 was denied the lock
Thread ID:15 was denied the lock
Thread ID:13 exiting lock
Thread ID:16 acquired the lock
Thread ID:17 was denied the lock
Thread ID:18 was denied the lock
Thread ID:16 exiting lock
Thread ID:19 acquired the lock
Thread ID:20 was denied the lock
Thread ID:21 was denied the lock
Thread ID:19 exiting lock
Thread ID:22 acquired the lock
Thread ID:22 exiting lock
Exchange sets the variable to the specified value and returns the original value, as an atomic operation. In a more typical scenario, where you would check the current variable value before setting it to the new value, it is possible that the executing thread could be persisted before performing the set operation, and another thread would be able to enter the code.