interlocked*()

Four system functions exist for thread-safe manipulation of Integer values. These four operations are atomic, and may be used on the same variables/fields from multiple threads, without risk of race conditions or value corruption, as long as all manipulation of the field goes through these methods.

interlockedInc() increments the variable passed into x by one, or by the optionally passed-in increment value. The old value of x is also returned as result:

method interlockedInc(var x: Integer; aIncrement: Integer := 1): Integer;
int interlockedInc(ref int x, int increment = 1)
func interlockedInc(_ x: ref Int, _ increment: Int = 1) -> Int
int interlockedInc(__ref int x, int increment = 1)

interlockedDec() decrements the variable passed into x by one, or by the optionally passed-in decrement value. The old value of x is also returned as result:

method interlockedDec(var x: Integer; aDecrement: Integer := 1): Integer;
int interlockedDec(ref int x, int increment = 1)
func interlockedDec(_ x: ref Int, _ increment: Int = 1) -> Int
int interlockedDec(__ref int x, int increment = 1)

interlockedExchange() overwrites the value of x with a new value. The old value of x is also returned as result:

method interlockedExchange(var x: Integer; aNewValue: Integer): Integer;
int interlockedExchange(ref inf x, int newValue);
func interlockedExchange(_ x: ref Int, _ newValue: Int) -> Int
int interlockedExchange(__ref inf x, int newValue);

interlockedCompareExchange() performs two actions in one atomic step: First, it compares the value of x to the comparison value. Only if they are equal, it will overwrite the value of x with the new value. The old value of x is also returned as result:

method interlockedCompareExchange(var x: Integer; aCompareTo: Integer; aNewValue: Integer): Integer;
int interlockedCompareExchange(ref int x, int compareTo, int newValue);
func interlockedCompareExchange(_ x: ref Int, _ compareTo: Int, _ newValue: Integer) -> Int
int interlockedCompareExchange(__ref int x, int compareTo, int newValue);

Supported Types

While the above signatures read Integer, these functions, much like inc() and dec(), support all of the following integer-based types:

  • .NET: Int32, Int64, IntPtr;
  • Cocoa: Enums, Int32, UInt32, Int64, UInt64, IntPtr, UIntPtr, ^Void
  • Java: These functions are not supported on Java, due to runtime limitations
  • Island: Enums, Int32, UInt32, Int64, UInt64, IntPtr, UIntPtr, ^Void

On .NET, interlockedExchange and interlockedCompareExchange additionally support Single and object references.

On Cocoa, interlockedCompareExchange also accepts records containing exactly two pointers.

See Also