Atomically reads a numeric value from a variable and writes a new value. Used for restricting access to data shared between threads.
old_value =Thread.TestAndSet(variable, new_value)
Prerequisites
None
Parameters
variable
A required numeric variable whose old value is first read and then overwritten.
new_value
A required numeric expression whose value is written to variable.
Remarks
This method permits a thread to read and write a variable value, without any possibility that another thread will change the value between the time it is read and the time it is written.
In a multi-threaded application, this permits procedures to be developed that interlock data structures that are accessed by more than one thread. This interlocking can avoid problems created by having one thread access a data structure that is invalid because its data is in the process of being modified by another thread.
Examples
' Thread-safe lock using Test and Set
Sub Lock (ByRef lock_var As Integer)
' Loop while someone else has the lock
While Thread.TestAndSet(lock_var, 1) <> 0
Thread.Sleep (0)
End While
End Sub
' Thread-safe unlock after using Test and Set
Sub Unlock (ByRef lock_var As Integer)
lock_var = 0
End Sub
' Thread-safe increment using Test and Set
Sub Inc_variable (ByRef inc_var As Integer)
Dim old_value As Integer
Do
old_value = inc_var
Loop While Thread.TestAndSet(inc_var,old_value+1) <> old_value
End Sub
See Also