How to address thread-safety of service data used for maintaining static local variables in C++?

后端 未结 4 620
隐瞒了意图╮
隐瞒了意图╮ 2020-12-30 15:31

Consider the following scenario. We have a C++ function with a static local variable:

void function()
{
    static int variable = obtain();
    //blahblablah         


        
4条回答
  •  佛祖请我去吃肉
    2020-12-30 16:01

    Some lateral dodges you can try that might solve your underlying problem:

    • you could make int variable be a thread-local static, if the different threads don't actually need to share the value of this variable or pass data to each other through it.
    • for an int on x86, you can use an atomic read/write such as by InterlockedCompareExchange() or its equivalent on your platform. This lets multiple threads safely access the variable without locks. It only works for hardware-native atomic types, though (eg, 32-bit and 64-bit words). You will also have to figure out what to do if two threads want to write to the variable at the same time (ie, one will discover that the other has written to it when it performs the compare-and-swap op).

提交回复
热议问题