Local static variables and multithreading

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Marcin Kalicinski

    #1

    Local static variables and multithreading

    I'm trying to write platform-independent code that will work correctly in
    multithreaded environment. I know C++ standard says nothing about threads,
    but I still think my question is not entirely off-topic here:

    int f()
    {
    static int n = g();
    return n;
    }

    If I call the above function from multiple threads, can I still assume that
    g() will only be called once? Or is it platform dependent?

    thank you,
    Marcin


  • John Carson

    #2
    Re: Local static variables and multithreading

    "Marcin Kalicinski" <kalita@poczta. onet.pl> wrote in message
    news:DoSvf.2597 8$f7.24888@news fe3-win.ntli.net[color=blue]
    > I'm trying to write platform-independent code that will work
    > correctly in multithreaded environment. I know C++ standard says
    > nothing about threads, but I still think my question is not entirely
    > off-topic here:
    > int f()
    > {
    > static int n = g();
    > return n;
    > }
    >
    > If I call the above function from multiple threads, can I still
    > assume that g() will only be called once?[/color]

    No.

    http://blogs.msdn.com/oldnewthing/ar.../08/85901.aspx

    Or is it platform dependent?

    I suspect the answer is no on any multithreaded platform.


    --
    John Carson



    Comment

    • abelikoff@gmail.com

      #3
      Re: Local static variables and multithreading

      In order to guarantee the above, the compiler would need to be aware of
      threads. It would actually need to generate code to handle that
      assignment inside a mutex or a critical section. C++ doesn't do that
      (yet).

      The code above can exhibit a number of nasty bugs: from duplicate
      invocation of g() to use of partially initialized n.

      -- Sasha

      Comment

      Working...