Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to NOT use Atomic Operations? [closed]

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!

like image 467
Eugene K Avatar asked Feb 11 '14 18:02

Eugene K


People also ask

Can atomic operation be interrupted?

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.

What is non-atomic operation?

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.

What are atomic operations used for?

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.

Are atomic operations thread-safe?

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() .


2 Answers

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.

like image 139
Sneftel Avatar answered Nov 07 '22 08:11

Sneftel


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.

like image 26
JaredPar Avatar answered Nov 07 '22 06:11

JaredPar