[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Library initialization with gettext is not thread-safe

From: Bruno Haible
Subject: Re: Library initialization with gettext is not thread-safe
Date: Fri, 08 Jul 2022 19:34:43 +0200

Vivien Kraus wrote:
> I may be wrong, but I think that reading libfoo_initialized (in
> create_foo) while another thread is modifying it (in libfoo_initialize)
> is undefined behavior, even for a bool.

Ah right. On some CPU types (e.g. IA64), the value is not propagated
between caches of different CPUs, unless the compiler arranges for it.
To tell the compiler to do so, either a 'volatile' marker or an
'atomic' type is needed (like you say).

> Having thought about it a bit more, I have found 2 solution:
> - Use an atomic variable for libfoo_initialized;
> - Use pthread_once.

You're right, both are proper solutions.

> However, atomic variables are quite a recent addition to C so I’m not
> sure it can be advertised in the manual.

Yes, atomics are still not fully portable in practice.

> And I don’t know much about pthread_once,

pthread_once would guarantee that the initialization function gets called
only once. But it is overkill here.

> I don’t know whether it works if create_foo is called
> from competing threads from different threading libraries (such as 2
> openmp threads for instance).

OpenMP threads are based on libc threads, which means POSIX threads on
Linux or Windows threads on Windows. So, from the perspective of
pthread_once, there is no difference between a main thread, a thread created
by pthread_create, or an OpenMP thread.

I've added this doc improvement:

Thanks for your good report!


reply via email to

[Prev in Thread] Current Thread [Next in Thread]