Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11: Is std::thread on linux depending on pthread library?

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?

like image 549
Hind Forsum Avatar asked Aug 11 '17 10:08

Hind Forsum


2 Answers

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++).

like image 87
Maxim Egorushkin Avatar answered Oct 23 '22 13:10

Maxim Egorushkin


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.

  1. 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!

  2. 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.

like image 29
Chris Beck Avatar answered Oct 23 '22 12:10

Chris Beck