I am just trying my hands on g++ 4.6
and C++11
features.
Every time I compile a simple threading code using -std=c++0x
flag, either it crashes with segmentation fault or it just throws some weird exception.
I read some questions related to C++11
threads and I realized that, I also need to use -pthread
flag to compile the code properly. Using -pthread
worked fine and I was able to run the threaded code.
My question is, whether the C++11
multi-threading model uses Pthreads
in the background?
Or is it written from the scratch?
I don't know if any of the members are gcc
contributors but I am just curious.
If you run g++ -v
it will give you a bunch of information about how it was configured. One of those things will generally be a line that looks like
Thread model: posix
which means that it was configured to use pthreads for its threading library (std::thread in libstdc++), and which means you also need to use any flags that might be required for pthreads on your system (-pthread
on Linux).
This has nothing specific to do with the standard, its just a detail of how the standard is implemented by g++
C++ doesn't specify how threads are implemented. In practice C++ threads are generally implemented as thin wrappers over pre-existing system thread libraries (like pthreads or windows threads). There is even a provision to access the underlying thread object with std::thread::native_handle().
The reason that it crashes is that if you do not specify -pthreads
or -lpthreads
, a number of weakly defined pthreads stub functions from libc
are linked. These stub functions are enough to get your program to link without error. However, actually creating a pthread requires the full on libpthread.a library, and when the dynamic linker (dl
) tries to resolve those missing functions, you get a segmentation violation.