I can think of reasons when it doesn't matter, and 1 situation where you may NOT want to use them which is when you want to test a design for behaviour with non-atomic operations.
What are some other reasons? Specifically I am working on a project that is having some rare race conditions, because a test is not using atomic increments. I am wondering, why would I not just always use atomic increments when a function for it already exists?
Thanks!
An atomic operation is one that cannot be interrupted. These operations are typically used for acquiring locks. If another process or thread writes to the lock variable between the lock comparison (lock == 0) and setting the lock (lock++), then the lock could fail to ensure exclusive action.
Non-Atomic CPU InstructionsA memory operation can be non-atomic even when performed by a single CPU instruction. For example, the ARMv7 instruction set includes the strd instruction, which stores the contents of two 32-bit source registers to a single 64-bit value in memory.
Atomic operations are sequences of instructions that guarantee atomic accesses and updates of shared single word variables. This means that atomic operations cannot protect accesses to complex data structures in the way that locks can, but they provide a very efficient way of serializing access to a single word.
A classic use of atomic operations is for thread-safe reference counting. Suppose x is a reference count of type int and the program needs to take some action when the reference count becomes zero. In single-threaded code, you could use a plain int for x , and write --x ; if(x==0) action() .
Because atomics are slower. They slow down the calling thread, and they may slow down other threads as well, potentially even ones not accessing the same atomics. They may also inhibit the compiler from performing certain reordering optimizations that it would otherwise perform.
Atomic operations are potentially, and likely, more expensive than their non-atomic equivalent. In cases where synchronization between threads isn't needed, for instance updating an unshared local, atomiticy adds unnecessary overhead and should be avoided.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With