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.
source share