Thread safe increment of static local variable

前端 未结 2 1458
野的像风
野的像风 2021-01-12 08:13
void foo() {
    static int id = 0;
    const int local_id = id++;
    //do something with local_id;
}

Multiple threads can call foo in parallel mu

相关标签:
2条回答
  • 2021-01-12 08:23

    Your code is not thread safe because two threads may increment id at the same time.

    Use mutual exclusion or std::atomic for the shared id variable.

    0 讨论(0)
  • 2021-01-12 08:26

    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;
    }
    
    0 讨论(0)
提交回复
热议问题