I read that pthread is C library and is not compatible with C++ object model, especially when talking about exception handling.
So I wish to know on linux system, how gcc/clang implements std::thread
, is it calling some linux native functions/kernel apis or something?
Also, how is std::thread_local
implemented, related with __thread
?
I read that pthread is C library and is not compatible with C++ object model, especially when talking about exception handling.
This information is inaccurate.
how gcc/clang implements
std::thread
They call a platform-specific thread creation function. On Linux it is pthread_create
. You can call this function directly.
When a thread throws an exception and it is not caught std::terminate
is called.
Note that your application must be compiled and linked with -pthread
flag (using -lpthread
is unnecessary and insufficient with both C and C++).
I read that pthread is C library and is not compatible with C++ object model, especially when talking about exception handling.
There's a statement in the neighborhood of this that is true, but this statement as written is not true.
There are two facts here.
If YOU call pthreads functions yourself, it is indeed just a C library, and you had better make sure you do everything correctly in regards to exception safety. If you pass function pointers to pthread_create_...
and those functions will throw exceptions... your program can have big problems. That should be obvious, it will be true whenever you talk to a C library from C++.
That does not mean it is impossible to use such a library with a C++ program!
pthread does not actually need to know about any of your objects, or any of their ctors or dtors, or any of that, in order to make your program multithreaded. All it needs to spawn a thread, is a function pointer, and that function pointer will have a completely C-compatible signature.
When the C++ compiler calls pthreads functions in order to implement std::thread
, the compiler is going to emit code that talks to pthread correctly. If it uses pthread in an illegal way to implement your C++ program, it's a bug in the compiler or standard library.
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