Linking with -pthread only if linking with a .so that needs it

Jonathan Wakely jwakely.gcc@gmail.com
Fri Apr 27 12:29:00 GMT 2018


On 24 April 2018 at 12:14, Sam Varshavchik wrote:
> I'd like to to understand a little bit better why it seems that I need to
> use -pthread to compile and link something that does not use execution
> threads, std::locks, or std::mutexes, but it links with several shared
> libraries that do. Without -pthread the link appears to be fine, but then I
> observe some instability in the initial static initialization, before
> main(), in those shared libraries' static initialization code.

Without looking into it in much detail, this could happen during a
static constructor in a shared library (or if you dlopen libpthread,
but it doesn't looks like you're doing that).

If the main application is not linked to libpthread then during
initialization of its global variables __gthread_active_p() will
return false. While loading your shared library libpthread.so gets
opened, and after that point __gthread_active_p will return true.

When your main application is linked directly to libpthread.so
__gthread_active_p() returns true earlier in the initialization phase,
before starting to load your shared library.

I don't know why the lambda capture matters, it might just change
order of initialization in some unspecified way.

I really want to move libstdc++ away from the current
__gthread_active_p because of problems like this. Ideally I'd like an
API in glibc that we can use to query whether any threads have
actually been created (not just whether libpthread.so is linked in).



More information about the Gcc-help mailing list