The difference between std :: atomic and std :: mutex

how to use std :: atomic <gt;

In the question above, obviously, we can simply use std::mutexto ensure 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--;
    }     
};
+4
source share
1 answer

As a rule, use std::atomicfor POD types, where the main specialization will be able to use something clever, like locking a bus on a CPU (which will not give you more extra costs than a pipeline dump) or even a spin lock. In some systems, it intmay already be atomic, therefore it std::atomic<int>will effectively specialize in int.

std::mutex -POD-, , , .

, .

+5

Source: https://habr.com/ru/post/1655328/


All Articles