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

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

    (I have post this on another question, but it is also an answer to this one)

    Here is my take (if really you can't initialize it before threads are launched):

    I've seen (and used) something like this to protect static initialization, using boost::once

    #include 
    
    boost::once_flag flag;
    
    // get thingy
    const Thingy & get()
    {
        static Thingy thingy;
    
        return thingy;
    }
    
    // create function
    void create()
    {
         get();
    }
    
    void use()
    {
        // Ensure only one thread get to create first before all other
        boost::call_once( &create, flag );
    
        // get a constructed thingy
        const Thingy & thingy = get(); 
    
        // use it
        thingy.etc..()          
    }
    

    In my understanding, this way all threads wait on boost::call_once except one that will create the static variable. It will be created only once and then will never be called again. And then you have no lock any more.

提交回复
热议问题