Why does specifying -std=c++11
when compiling a program that directly or indirectly uses std::thread
not imply -pthread
? It seems strange that the implementation detail of std::thread
using pthreads under the hood is exposed to the programmer; if it's a matter of giving the user a choice of posix-compatible threading libraries, why not just default to pthreads and have some --threading-model=<your_favorite_posix_threads_library>
argument to override it?
std::thread is the thread class that represents a single thread in C++. To start a thread we simply need to create a new thread object and pass the executing code to be called (i.e, a callable object) into the constructor of the object. Once the object is created a new thread is launched which will execute the code specified in callable.
It seems that for cross-platform threading implementation, the GCC standard library relies on the gthreads/pthreads library. If this library is not available, as is the case with MinGW, the classes std::thread, std::mutex, std::condition_variable are not defined.
Yes, GCC always uses libstdc++ unless you tell it to use no standard library at all with the -nostdlib option (in which case you either need to avoid using any standard library features, or use -I and -L and -l flags to point it to an alternative set of header and library files).
On Mac OS X sometimes the gcc and g++ commands are actually aliases for Clang not GCC, and the version of libstdc++ that Apple ships is ancient (circa 2008) so of course it doesn't support C++11.
The -pthread
option is not universally required to use std::thread
- it's an implementation quirk of whatever platform you're building on.
Compiling:
#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++
On 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've needed to link nothing extra to make this work - nor has it happened behind the scenes. It seems to be very much a platform implementation detail that pthreads is a separate library.
Having a choice of threading libraries with the pthread interface is legacy baggage on *NIX systems, many of which started off without thread support, then went through a phase of user-space threads before having full kernel support. I guess it's still there because nobody likes making breaking changes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With