Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The difference btween std::atomic and std::mutex

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--;
    }     
};
like image 617
Yves Avatar asked Sep 21 '16 12:09

Yves


People also ask

What is the difference between mutex and Atomic?

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.

Is Atomic better than mutex?

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.

What is std :: atomic for?

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 .

Is Pthread mutex lock Atomic?

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.


1 Answers

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.

like image 117
Bathsheba Avatar answered Sep 22 '22 13:09

Bathsheba