void foo() { static int id = 0; const int local_id = id++; //do something with local_id; }
Multiple threads can call foo in parallel several times. I want every call to foo to use the "unique" value of local_id. Is this normal with the above code? I wonder if the second thread is assigned the id local_id value before the value is incremented by the first thread. If this is not safe, is there a standard solution for this?
Your code is not thread safe because multiple threads can read idat the same time and create the same value local_id.
id
local_id
, std::atomic_int, ++ 11:
std::atomic_int
void foo() { static std::atomic_int id; const int local_id = id++; //do something with local_id; }
, .
std:: atomic id.