Usually when building thread related code in GCC, explicit linking against pthread is necessary:
g++ -pthread main.cxx
However, the following code compiles, links, and runs fine without being linked against pthread:
#include <iostream>
#include <thread>
using namespace std::chrono_literals;
int main() {
std::this_thread::sleep_for(1000ms);
return 0;
}
I guess what is happening here is that std::this_thread::sleep_for
is using some POSIX function from libc (instead of something from pthread)? But if that is the case, does the execution of std::this_thread::sleep_for
change depending on whether or not it was called from the main thread?
Why doesn't this_thread::sleep_for need to be linked against pthread?
Because the call to std::this_thread::sleep_for
translates into underlying call to nanosleep
, which is defined in libc.so.6
, and not in libpthread.so.0
.
Note that when linking with GLIBC-2.34 and later, using other functions (which previously required -pthread
) no longer require it, because GLIBC got rid of libpthread
.
See also this answer.