Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread safe increment of 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 multiple times. I want each call of foo use "unique" value of local_id. Is it ok with the above code? I wonder if second thread assign the value of id to local_id before the value is increased by the first thread. If it is not safe, is there any standard solution for this?

like image 240
strugi Avatar asked Oct 28 '14 14:10

strugi


1 Answers

Your code is not thread-safe, because multiple threads can read id concurrently, and producing the same value of local_id.

If you want a thread-safe version, use std::atomic_int, which is available in C++11:

void foo() {
    static std::atomic_int id;
    const int local_id = id++;
    //do something with local_id;
}
like image 178
Sergey Kalinichenko Avatar answered Oct 21 '22 14:10

Sergey Kalinichenko