Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

atomic increment and return 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.

like image 330
Anonymous Entity Avatar asked Dec 18 '16 09:12

Anonymous Entity


People also ask

What is atomic counter?

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.

Is increment an atomic operation?

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.


2 Answers

Simply use:

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

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

like image 195
Jarod42 Avatar answered Oct 07 '22 20:10

Jarod42


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++; 
like image 28
Pete Becker Avatar answered Oct 07 '22 20:10

Pete Becker