Interlocked Class
Provides atomic operations for variables that are shared by multiple threads.
Namespace: System.Threading
Assembly: Mscorlib (in mscorlib.dll)
Syntax
VB
C#
C++
F#
JScript
Copy
'Declaration
Public NotInheritable Class Interlocked
Remarks
The methods of this class help protect against errors that can occur when the scheduler switches contexts while a thread is updating a variable that can be accessed by other threads, or when two threads are executing concurrently on separate processors. The members of this class do not throw exceptions.
The Increment and Decrement methods increment or decrement a variable and store the resulting value in a single operation. On most computers, incrementing a variable is not an atomic operation, requiring the following steps:
1.
Load a value from an instance variable into a register.
2.
Increment or decrement the value.
3.
Store the value in the instance variable.
If you do not use Increment and Decrement, a thread can be preempted after executing the first two steps. Another thread can then execute all three steps. When the first thread resumes execution, it overwrites the value in the instance variable, and the effect of the increment or decrement performed by the second thread is lost.
The Exchange method atomically exchanges the values of the specified variables. The CompareExchange method combines two operations: Comparing two values and storing a third value in one of the variables, based on the outcome of the comparison. The compare and exchange operations are performed as an atomic operation.
Examples
The following code example shows a thread-safe resource locking mechanism.
VB
C#
C++
F#
JScript
Copy
Imports System
Imports System.Threading
Namespace InterlockedExchange_Example
Class MyInterlockedExchangeExampleClass
'0 for false, 1 for true.
Private Shared usingResource As Integer = 0
Private Const numThreadIterations As Integer = 5
Private Const numThreads As Integer = 10
_
Shared Sub Main()
Dim myThread As Thread
Dim rnd As New Random()
Dim I As Integer
For I = 0 To numThreads - 1
myThread = New Thread(AddressOf MyThreadProc)
myThread.Name = String.Format("Thread{0}", I + 1)
'Wait a random amount of time before starting next thread.
Thread.Sleep(rnd.Next(0, 1000))
myThread.Start()
Next I
End Sub 'Main
Private Shared Sub MyThreadProc()
Dim I As Integer
For I = 0 To numThreadIterations - 1
UseResource()
'Wait 1 second before next attempt.
Thread.Sleep(1000)
Next I
End Sub
'A simple method that denies reentrancy.
Shared Function UseResource() As Boolean
'0 indicates that the method is not in use.
If 0 = Interlocked.Exchange(usingResource, 1) Then
Console.WriteLine("{0} acquired the lock", Thread.CurrentThread.Name)
'Code to access a resource that is not thread safe would go here.
'Simulate some work
Thread.Sleep(500)
Console.WriteLine("{0} exiting lock", Thread.CurrentThread.Name)
'Release the lock
Interlocked.Exchange(usingResource, 0)
Return True
Else
Console.WriteLine(" {0} was denied the lock", Thread.CurrentThread.Name)
Return False
End If
End Function
End Class
End Namespace
Provides atomic operations for variables that are shared by multiple threads.
Namespace: System.Threading
Assembly: Mscorlib (in mscorlib.dll)
Syntax
VB
C#
C++
F#
JScript
Copy
'Declaration
Public NotInheritable Class Interlocked
Remarks
The methods of this class help protect against errors that can occur when the scheduler switches contexts while a thread is updating a variable that can be accessed by other threads, or when two threads are executing concurrently on separate processors. The members of this class do not throw exceptions.
The Increment and Decrement methods increment or decrement a variable and store the resulting value in a single operation. On most computers, incrementing a variable is not an atomic operation, requiring the following steps:
1.
Load a value from an instance variable into a register.
2.
Increment or decrement the value.
3.
Store the value in the instance variable.
If you do not use Increment and Decrement, a thread can be preempted after executing the first two steps. Another thread can then execute all three steps. When the first thread resumes execution, it overwrites the value in the instance variable, and the effect of the increment or decrement performed by the second thread is lost.
The Exchange method atomically exchanges the values of the specified variables. The CompareExchange method combines two operations: Comparing two values and storing a third value in one of the variables, based on the outcome of the comparison. The compare and exchange operations are performed as an atomic operation.
Examples
The following code example shows a thread-safe resource locking mechanism.
VB
C#
C++
F#
JScript
Copy
Imports System
Imports System.Threading
Namespace InterlockedExchange_Example
Class MyInterlockedExchangeExampleClass
'0 for false, 1 for true.
Private Shared usingResource As Integer = 0
Private Const numThreadIterations As Integer = 5
Private Const numThreads As Integer = 10
_
Shared Sub Main()
Dim myThread As Thread
Dim rnd As New Random()
Dim I As Integer
For I = 0 To numThreads - 1
myThread = New Thread(AddressOf MyThreadProc)
myThread.Name = String.Format("Thread{0}", I + 1)
'Wait a random amount of time before starting next thread.
Thread.Sleep(rnd.Next(0, 1000))
myThread.Start()
Next I
End Sub 'Main
Private Shared Sub MyThreadProc()
Dim I As Integer
For I = 0 To numThreadIterations - 1
UseResource()
'Wait 1 second before next attempt.
Thread.Sleep(1000)
Next I
End Sub
'A simple method that denies reentrancy.
Shared Function UseResource() As Boolean
'0 indicates that the method is not in use.
If 0 = Interlocked.Exchange(usingResource, 1) Then
Console.WriteLine("{0} acquired the lock", Thread.CurrentThread.Name)
'Code to access a resource that is not thread safe would go here.
'Simulate some work
Thread.Sleep(500)
Console.WriteLine("{0} exiting lock", Thread.CurrentThread.Name)
'Release the lock
Interlocked.Exchange(usingResource, 0)
Return True
Else
Console.WriteLine(" {0} was denied the lock", Thread.CurrentThread.Name)
Return False
End If
End Function
End Class
End Namespace