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

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


On 27 April 2018 at 13:48, Sam Varshavchik wrote:
> Jonathan Wakely writes:
>
>> 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).
>
>
> Right. This is is a static constructor in the shared library.
>
>> 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.
>
>
> But that static constructor is in the shared library that's linked with
> libpthread. The static constructor did a std::mutex::lock followed by
> std::mutex::unlock, and it seemed like only the unlock thought libpthread
> wasn't linked in. lock() incremented the counter in the mutex, and put its
> pid in there. unlock() left the mutex untouched, leaving it in locked state.

Huh, that is strange.

> No threads were created at that point, during initialization. The app code
> in question does not create threads until main() runs.

__gthread_active_p only cares about whether libpthread.so is linked in
to the program, it can't know if any threads have been created.



More information about the Gcc-help mailing list