Thread-safe initialization of function-local static const objects

后端 未结 8 1431
悲&欢浪女
悲&欢浪女 2020-12-28 16:41

This question made me question a practice I had been following for years.

For thread-safe initialization of function-local static const objects I protect t

相关标签:
8条回答
  • 2020-12-28 17:07

    Just call the function before you start creating threads, thus guaranteeing the reference and the object. Alternatively, don't use such a truly terrible design pattern. I mean, why on earth have a static reference to a static object? Why even have static objects? There's no benefit to this. Singletons are a terrible idea.

    0 讨论(0)
  • 2020-12-28 17:09

    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/thread/once.hpp>
    
    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.

    0 讨论(0)
提交回复
热议问题