Step-by-step increase in a static local variable

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?

+4
source share
2 answers

Your code is not thread safe because multiple threads can read idat the same time and create the same value local_id.

, std::atomic_int, ++ 11:

void foo() {
    static std::atomic_int id;
    const int local_id = id++;
    //do something with local_id;
}
+5

, .

std:: atomic id.

0

All Articles