Atomic increment and return counter

Trying to create a unique id generation function and came up with the following:

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

But I guess that this function can return the same value twice, right? For example, stream A calls a function, increases the value, but then stops when stream B enters, and also increases the value, finally A and B return the same value.

Thus, using mutexes, a 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: is it possible to create spawning behavior for unique int values ​​from a counter using only atomics? The reason I ask is because I need to create many identifiers, but read that the mutex is slow.

+5
source share
2 answers

Just use:

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

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

+6
source

Two pieces of code do two different things.

 id++; return id.load(); 

this code increments id and then returns an incremented value.

 std::lock_guard<std::mutex> lock{mx}; return id++; 

this code returns the value before the increment.

The correct code to be done first is

 return ++id; 

The correct code to execute the second is

 return id++; 
+3
source

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


All Articles