Why is -pthread necessary to use std :: thread in GCC and Clang?

Why -std=c++11 n't specifying -std=c++11 when compiling a program that uses std::thread directly or indirectly doesn't mean -pthread ? It seems strange that the implementation detail of std::thread using pthreads under the hood is exposed to the programmer; if it is a matter of giving the user a choice of posix-compatible thread libraries, why not just use pthreads by default and use the --threading-model=<your_favorite_posix_threads_library> to replace it?

+6
source share
1 answer

It is not necessary to use -pthread to use std::thread - this is a quirk of implementing any platform you are building on.

Compilation:

 #include <thread> #include <iostream> int main() { std::thread t{[]() { std::cout << "Hello World\n"; }}; t.join(); return 0; } 

with

 clang -std=c++11 ThreadTest.cpp -lc++ 

In MacOSX, builds and runs, and if we do:

 otool -L a.out a.out: /usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 120.1.0) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1225.0.0) 

We can see that we did not need to bind anything superfluous in order to do this work - and this did not happen behind the scenes. This seems to be a very important part of the platform implementation, in which pthreads is a separate library.

The presence of a library of threads with the pthread interface is an outdated baggage on * NIX systems, many of which started without thread support, and then went through the user space thread phase to full kernel support. I guess it still exists because no one likes to do hacks.

+2
source

All Articles