Search code examples
c++multithreadingatomicstdatomic

How to implement an atomic counter


Trying to make a unique id generating function, and came up with this:

std::atomic<int> id{0};
int create_id() {
    id++;
    return id.load();
}

But I assume it's possible for that function to return the same value twice, right? For example, thread A calls the function, increments the value, but then halts while thread B comes in and also increments the value, finally A and B both return the same value.

So using mutexes, the function might look like this:

std::mutex mx;
int id = 0;
int create_id() {
    std::lock_guard<std::mutex> lock{mx};
    return id++;
}

My question: Is it possible to create the behavior of spawning unique int values from a counter using only atomics? The reason I'm asking is because I need to spawn a lot of id's, but read that mutex is slow.


Solution

  • Simply use:

    std::atomic<int> id{};
    
    int create_id() {
        return id++;
    }
    

    See http://en.cppreference.com/w/cpp/atomic/atomic/operator_arith