通常在 GCC 中構建執行緒相關代碼時,需要針對 pthread 進行顯式鏈接:
g -pthread main.cxx
但是,以下代碼在不與 pthread 鏈接的情況下編譯、鏈接和運行良好:
#include <iostream>
#include <thread>
using namespace std::chrono_literals;
int main() {
std::this_thread::sleep_for(1000ms);
return 0;
}
我猜這里發生的事情std::this_thread::sleep_for是使用 libc 中的一些 POSIX 函式(而不是 pthread 中的某些函式)?但如果是這種情況,是否std::this_thread::sleep_for會根據是否從主執行緒呼叫來更改執行?
uj5u.com熱心網友回復:
為什么 this_thread::sleep_for 不需要與 pthread 鏈接?
因為對的呼叫std::this_thread::sleep_for轉換為對的底層呼叫nanosleep,它在 中定義libc.so.6,而不是在 中定義libpthread.so.0。
請注意,當與 GLIBC-2.34 及更高版本鏈接時,使用其他功能(以前需要-pthread)不再需要它,因為GLIBC 擺脫了libpthread.
另請參閱此答案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/407127.html
標籤:
