Boost logo

Boost :

From: Martin Bonner (martin.bonner_at_[hidden])
Date: 2005-08-01 04:49:35


----Original Message----
From: Jason Hise [mailto:chaos_at_[hidden]]
Sent: 01 August 2005 02:35
To: boost_at_[hidden]
Subject: [boost] singleton and thread safety

> I need to ensure that certain objects (specifically the policy bundles
> which manage singleton instances) are created in a thread-safe manner.
> First question: Can two threads both initialize the same static
> variable if they pass through the same function at the same time? Ex:
>
> void foo ( )
> {
> static Thing t;
> }
>
> Can t's constructor be called twice by two threads executing foo?

The standard is silent on the issue (because it doesn't address threading).
You would need to consult the documentation of each supported compiler.

I can't find the documentation for VC7.1, but looking at the generated code,
it appears that t's constructor CAN be called twice.

> If so, I feel that I need to construct my policy bundles before
> execution enters main, a time when it is pretty much guaranteed that
> the application is operating in a single-threaded context. I thought
> that this would be simple to do: just write a class that calls the
> function with the static variable in its constructor and create
> a global instance of that class. However, the standard appears to
> say that initialization of such global variables can happen after main
> is entered, so long as it happens before the global variable is used. #

It does say that. In practise (and ignoring DLLs), no implementation takes
advantage of that freedom. This is because it is quite easy to set up
situations where A must be initialized before B, but B must also be
initialized before A. (If the initialization occurs before main(), then the
guarantees which cause the problem don't apply).

> If the program starts
> spawning threads before the global variable is constructed I would
> still have the same problem.
>
> How can I ensure that initialization is performed before main is
> entered?
It is almost certainly safe to assume that globals are initialized before
main is entered (ignoring dynamic libraries).

If you don't want to ignore dynamic libraries, I am not sure how to proceed
(except to say that it is tricky)!

> If I cannot, is there some other way to make initialization
> of static variables thread-safe?
Lock a mutex.

> I cannot lock a mutex to manage this,
> because the mutex lives inside the threading policy instance and the
> threading policy instance lives in the policy bundle that I am trying
> to create in the first place.

 :-)

-- 
Martin Bonner
Martin.Bonner_at_[hidden]
Pi Technology, Milton Hall, Ely Road, Milton, Cambridge, CB4 6WZ,
ENGLAND Tel: +44 (0)1223 441434

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk