gcc static constructor multi-threading flaw

Joe Buehler jbuehler@hekimian.com
Fri Feb 14 15:09:00 GMT 2003

Christopher (Faylor):

Would you accept patches to gcc / cygwin to add locking to
function-private static object constuction?

Gcc generates calls to atexit() when entering a function
that has a private static object.  It does this to schedule
a call to the destructor at program exit time.

The atexit() function is not thread-safe, however.  I posted
an explanation to the newlib list, but looking at the newlib
code, it appears that newlib is not really set up for locking,
so a fix is probably not going to be forthcoming from there.

One possible fix is to have gcc call a wrapper function
that performs locking and then calls atexit().  I suppose
another way to do it without touching gcc is #define
manipulation to replace atexit() with a Cygwin wrapper.

The reason for all this is that I sometimes get crashes in
cygwin processes at program exit time because of corruption
of atexit() internal data.  Any multi-threaded Cygwin app is
going to risk this problem.  There are currently 4 such
objects in cygwin1.dll itself.  No idea how many there are
when you count all the apps.

Note that this is not a total fix.  As I recall, the code
generated by gcc is inherently not thread-safe -- it's testing
a global to see whether to do the constructor/destructor code
block, and there is a race condition.
Joe Buehler

More information about the Cygwin-developers mailing list