Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How fast is access to atomic variables in C++

Tags:

c++

c++11

atomic

My question is how fast is access to atomic variables in C++ by using the C++0x actomic<> class? What goes down at the cache level. Say if one thread is just reading it, would it need to go down to the RAM or it can just read from the cache of the core in which it is executing? Assume the architecture is x86.

I am especially interested in knowing if a thread is just reading from it, while no other thread is writing at that time, would the penalty would be the same as for reading a normal variable. How atomic variables are accessed. Does each read implicity involves a write as well, as in compare-and-swap? Are atomic variables implemented by using compare-and-swap?

like image 224
MetallicPriest Avatar asked Aug 29 '11 13:08

MetallicPriest


People also ask

How fast is STD Atomic?

std::atomic<bool> On average, the execution time is 0.38 seconds.

What is atomic access in C?

Atomics as part of the C language are an optional feature that is available since C11. Their purpose is to ensure race-free access to variables that are shared between different threads. Without atomic qualification, the state of a shared variable would be undefined if two threads access it concurrently.

Is atomic int lock-free?

atomic<T> variables don't use locks (at least where T is natively atomic on your platform), but they're not lock-free in the sense above. You might use them in the implementation of a lock-free container, but they're not sufficient on their own.

What is atomic memory access?

An atomic access is a term for a series of accesses to a memory region. Atomic accesses are used by managers when they would like to perform a sequence of accesses to a particular memory region, while being sure that the original data in the region are not corrupted by writes from other managers.


1 Answers

The answer is not as simple as you perhaps expect. It depends on exact CPU model, and it depends on circumstances as well. The worst case is when you need to perform read-modify-write operation on a variable and there is a conflict (what exactly is a conflict is again CPU model dependent, but most often it is when another CPU is accessing the same cache line).

See also .NET or Windows Synchronization Primitives Performance Specifications

like image 149
Suma Avatar answered Oct 31 '22 20:10

Suma