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.
An Atomic Counter is a GLSL variable type whose storage comes from a Buffer Object. Atomic counters, as the name suggests, can have atomic memory operations performed on them. They can be thought of as a very limited form of buffer image variable.
The increment-memory machine instruction on an X86 is atomic only if you use it with a LOCK prefix. x++ in C and C++ doesn't have atomic behavior.
Simply use:
std::atomic<int> id; int create_id() { return id++; }
See http://en.cppreference.com/w/cpp/atomic/atomic/operator_arith
Your two code snippets do two different things.
id++; return id.load();
that code increments id
, then returns the incremented value.
std::lock_guard<std::mutex> lock{mx}; return id++;
that code returns the value before the increment.
The correct code to do what the first tries to do is
return ++id;
The correct code to do what the second does is
return id++;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With