how to use std::atomic<>
In the question above, obviously we can just use std::mutex
to keep thread safety. I want to know when to use which one.
classs A
{
std::atomic<int> x;
public:
A()
{
x=0;
}
void Add()
{
x++;
}
void Sub()
{
x--;
}
};
and
std::mutex mtx;
classs A
{
int x;
public:
A()
{
x=0;
}
void Add()
{
std::lock_guard<std::mutex> guard(mtx);
x++;
}
void Sub()
{
std::lock_guard<std::mutex> guard(mtx);
x--;
}
};
A mutex is a data structure that enables you to perform mutually exclusive actions. An atomic operation, on the other hand, is a single operation that is mutually exclusive, meaning no other thread can interfere with it. Many programming languages provide classes with names like “lock” or “mutex” and a lock method.
atomic integer is a user mode object there for it's much more efficient than a mutex which runs in kernel mode. The scope of atomic integer is a single application while the scope of the mutex is for all running software on the machine. This is almost true.
std::atomic compiles to lock addq . The LOCK prefix makes the following inc fetch, modify and update memory atomically. our explicit inline assembly LOCK prefix compiles to almost the same thing as std::atomic , except that our inc is used instead of add .
If however the mutex is locked, the thread blocks until the thread holding the lock calls unlock. Locking a mutex is an atomic operation, meaning that the operating system (or threads library) assures you that if you locked a mutex, no other thread succeeded in locking this mutex at the same time.
As a rule of thumb, use std::atomic
for POD types where the underlying specialisation will be able to use something clever like a bus lock on the CPU (which will give you no more overhead than a pipeline dump), or even a spin lock. On some systems, an int
might already be atomic, so std::atomic<int>
will specialise out effectively to an int
.
Use std::mutex
for non-POD types, bearing in mind that acquiring a mutex is at least an order of magnitude slower than a bus lock.
If you're still unsure, measure the performance.
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