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

后端 未结 4 596
隐瞒了意图╮
隐瞒了意图╮ 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:02

    To avoid the locking in any case, you can go with this:

    void functionThreadSafe()
    {
        static int *variable = 0;
        if (variable == 0)
        {
           CriticalSectionLockClass lock( criticalSection );
           // Double check for initialization in different thread
           if (variable == 0)
           {
              variable = new int(obtain());
           }
        }
        //blahblablah
    }
    

提交回复
热议问题