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

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

    C++ says that your static variable should only be initialized once - however C++ doesn't deal with threads(yet).

    gcc(atleast on *nix systems) does the proper magic to safely guard multiple threads initializing such a static variable. According to http://social.msdn.microsoft.com/Forums/en/vcgeneral/thread/12f8e2c7-d94d-4904-8c79-a0b0d1088e0b , msvc does not - and in such a case you'll have to lock the initialization yourself.

    Guarding the initialization with a critical section should protect all this - i.e. your functionThreadSafe() is ok - (unless obtain() itself calls functionThreadSafe()

    http://blogs.msdn.com/b/oldnewthing/archive/2004/03/08/85901.aspx is worth a read in this regard.

    Personally, to avoid surprises I'd try to rewrite this so you can initialize variable yourself, once, before you create any threads - e.g.

    static int variable = 0;
    void init_variable() //call this once, at the start of main()
    {
      variable = obtain();
    }
    
    void function() 
    {
      //use variable, lock if you write to it
    }
    

提交回复
热议问题