
On Thu, 2005-08-18 at 11:22 +0000, James E Taylor wrote:
Are you sure there are no guarantees for function scope statics?
I think the following is thread safe:
void my_func() { static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_lock(&m); // do something once pthread_mutex_unlock(&m); }
because the C-style PTHREAD_MUTEX_INITIALIZER doesn't involve a constructor call: the static is initialised before _any_ threads are running.
Also, constructors of global statics are not guaranteed to be single-threaded for the same reason you can't safely reference one static from the constructor of another (The Static Initialisation Order Fiasco); one constructor could create a thread that goes and uses an uninitialised static, whilst the main thread tries to initialise it.
Do you know whether the mutex ctor is thread-safe?
Well, like I said, I think this is all undefined or at least
implementation dependent. This is what my pthread docs say about the
above code, though:
man pthread_mutex_init:
Without static initialization, a self-initializing routine foo() might
look as follows:
static pthread_once_t foo_once = PTHREAD_ONCE_INIT;
static pthread_mutex_t foo_mutex;
void foo_init()
{
pthread_mutex_init(&foo_mutex, NULL);
}
void foo()
{
pthread_once(&foo_once, foo_init);
pthread_mutex_lock(&foo_mutex);
/* Do work. */
pthread_mutex_unlock(&foo_mutex);
}
With static initialization, the same routine could be coded as follows:
static pthread_mutex_t foo_mutex = PTHREAD_MUTEX_INITIALIZER;
void foo()
{
pthread_mutex_lock(&foo_mutex);
/* Do work. */
pthread_mutex_unlock(&foo_mutex);
}
....
End quote
--
t. scott urban