This question delves into creating a 64-bit atomic counter from 32-bit atomic integers. The counter has a single writer and multiple readers, with the writer being a signal handler that must not block.
The proposed solution employs a generation count, using the low bit as a read lock. Readers retry until the generation count is stable across the read, and the low bit is unset.
The code provided generally follows the correct design principles of a SeqLock, a known pattern for implementing lock-free atomic counters with sequence numbers. The use of memory ordering is sound, ensuring that the counter is updated atomically.
However, it's worth noting that using atomic RMW operations for the increment of the payload is unnecessary if the system supports cheaper 64-bit atomic addition or load. Instead, a simple load of both halves, followed by a non-atomic increment, and atomic storage of the result is sufficient.
Additionally, the sequence counter can also avoid atomic RMW operations unless it's used as a spinlock with multiple writers. With a single writer, it can use pure loads and pure stores with release ordering, which are more efficient than atomic RMW or stores with seq_cst ordering.
To bypass the limitations of atomic
Another alternative would be to implement a SeqLock template that dynamically checks if the target supports lock-free atomic operations on atomic
In conclusion, while the code provided presents a functional implementation of a 64-bit atomic counter using 32-bit atomics, there are potential optimizations and alternatives that could improve performance and simplify the code.
The above is the detailed content of How Can a 64-Bit Atomic Counter Be Implemented Using Only 32-Bit Atomics?. For more information, please follow other related articles on the PHP Chinese website!