Atomic Operations
For simple concurrent access to integers, booleans, or reference types, atomic operations provide a lock-free, efficient solution. Atomic operations are directly supported by hardware and don't require explicit lock mechanisms.
Cangjie provides various atomic types, such as AtomicInt64, AtomicBool, and AtomicReference. Atomic operations for integer types include load() for reading, store() for writing, fetchAdd() for atomic addition, compareAndSwap() for compare-and-swap, and more.
Atomic operations are suitable for simple scenarios like counting and flagging. If you need to protect compound operations on multiple variables, or if the critical section contains complex logic, you should use Mutex instead of atomic operations.
The code on the right uses AtomicInt64 to implement a thread-safe counter. fetchAdd(1) atomically increments the value by 1 and returns the value before modification. This approach is more lightweight and performs better than Mutex.
fetchAdd returns the value before modification, not the value after modification. To get the current value, use load().Try changing fetchAdd to a combination of regular store and load to see if data races occur.