Types and operations for atomic operations and lockless algorithms.
Example: cmd: --threads:on
import threading/atomics # Atomic var loc: Atomic[int] loc.store(4) assert loc.load == 4 loc.store(2) assert loc.load(Relaxed) == 2 loc.store(9) assert loc.load(Acquire) == 9 loc.store(0, Release) assert loc.load == 0 assert loc.exchange(7) == 0 assert loc.load == 7 var expected = 7 assert loc.compareExchange(expected, 5, Relaxed, Relaxed) assert expected == 7 assert loc.load == 5 assert not loc.compareExchange(expected, 12, Relaxed, Relaxed) assert expected == 5 assert loc.load == 5 assert loc.fetchAdd(1) == 5 assert loc.fetchAdd(2) == 6 assert loc.fetchSub(3) == 8 loc.atomicInc(1) assert loc.load == 6
Types
Ordering {.pure.} = enum Relaxed, ## No ordering constraints. Only the atomicity and ordering against ## other atomic operations is guaranteed. Consume, ## This ordering is currently discouraged as it's semantics are ## being revised. Acquire operations should be preferred. Acquire, ## When applied to a load operation, no reads or writes in the ## current thread can be reordered before this operation. Release, ## When applied to a store operation, no reads or writes in the ## current thread can be reorderd after this operation. AcqRel, ## When applied to a read-modify-write operation, this behaves like ## both an acquire and a release operation. SeqCst ## Behaves like Acquire when applied to load, like Release when ## applied to a store and like AcquireRelease when applied to a ## read-modify-write operation. ## Also guarantees that all threads observe the same total ordering ## with other SeqCst operations.
- Specifies how non-atomic operations can be reordered around atomic operations. Source Edit
Procs
proc compareExchange[T](location: var Atomic[T]; expected: var T; desired: T; order: Ordering = SeqCst): bool
- Atomically compares the value of the atomic object with the expected value and performs exchange with the desired one if equal or load if not. Returns true if the exchange was successful. Source Edit
proc compareExchange[T](location: var Atomic[T]; expected: var T; desired: T; success, failure: Ordering): bool
- Same as above, but allows for different memory orders for success and failure. Source Edit
proc compareExchangeWeak[T](location: var Atomic[T]; expected: var T; desired: T; order: Ordering = SeqCst): bool
- Same as above, but is allowed to fail spuriously. Source Edit
proc compareExchangeWeak[T](location: var Atomic[T]; expected: var T; desired: T; success, failure: Ordering): bool
- Same as above, but allows for different memory orders for success and failure. Source Edit