Local static variable define is thread safe?

Discussion in 'C++' started by kiluyar, May 22, 2007.

  1. kiluyar

    kiluyar Guest

    I have such a function:

    class T
    {
    public:
    T(){...//some operations}
    };


    T& GetInst()
    {
    static T t;
    return t;
    }

    I'm not sure whether this is thread safe? If T's constructor has many
    operations, when two thread entered this function early and later, is
    there such scenario: the first thread is in T's constructor's, the
    second thread define t again?
    kiluyar, May 22, 2007
    #1
    1. Advertising

  2. * kiluyar:
    > I have such a function:
    >
    > class T
    > {
    > public:
    > T(){...//some operations}
    > };
    >
    >
    > T& GetInst()
    > {
    > static T t;
    > return t;
    > }
    >
    > I'm not sure whether this is thread safe? If T's constructor has many
    > operations, when two thread entered this function early and later, is
    > there such scenario: the first thread is in T's constructor's, the
    > second thread define t again?



    The current version of the standard completely ignores the existence of
    threads (and almost completely ignores the existence of dynamic
    libraries). Therefore, the code is not thread safe. But you can use
    environment-specific means to make e.g. the initialization of the static
    variable thread safe. One simple way is to call GetInst() when only the
    main thread has started, no others yet started. Another way, less
    efficient, to ensure mutual exclusion for calls to GetInst. A third
    way, if it's OK to let each thread have its own T object, to use thread
    local storage. Boost threads support all three solutions. Of course,
    the first one doesn't require any special support, so the support
    consists of nothing, but by definition it's there... ;-)


    --
    A: Because it messes up the order in which people normally read text.
    Q: Why is it such a bad thing?
    A: Top-posting.
    Q: What is the most annoying thing on usenet and in e-mail?
    Alf P. Steinbach, May 22, 2007
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. S
    Replies:
    2
    Views:
    3,916
  2. Patrick Hoffmann
    Replies:
    3
    Views:
    2,816
    Christian Jan├čen
    Aug 8, 2003
  3. Kumar

    static variable thread safe?

    Kumar, Jan 10, 2004, in forum: C Programming
    Replies:
    6
    Views:
    8,187
    CBFalconer
    Jan 10, 2004
  4. Gabriel Rossetti
    Replies:
    0
    Views:
    1,298
    Gabriel Rossetti
    Aug 29, 2008
  5. John Nagle
    Replies:
    5
    Views:
    454
    John Nagle
    Mar 12, 2012
Loading...

Share This Page