有了GCC,你可以從std::thread::native_handle_type
構建一個std::thread::id
,但是你不能從它構造一個std::thread
。
這意味着您可以測試給定pthread_t
是否引用與std::thread
對象(或this_thread::get_id()
)相同的線程,但無法從中創建新的thread
對象。
A std::thread
被設計爲獨特處理線程。不同的thread
對象獲取底層線程的所有權的唯一方法是將其從原始線程移出,因此只有一個對象一次「擁有」它。如果你可以從本地手柄構建它們你可以這樣做:
// start new thread
std::thread t(&thread_func);
// now have two handles to the same thread
std::thread t2(t.native_handle());
std::thread t1.join();
// erm, hang on, this isn't right
std::thread t2.join();
這樣做的動機是,它可能需要使用本機平臺線程API建立一個線程,例如,特定的親和力或特定的堆棧大小(或其他一些無法通過C++ 11 API訪問的特性)。
理想的平臺將讓你當你構建線程,這樣可以讓你使用這些特定於平臺的功能,而無需通過構建削弱類型的系統指定參數,如親和力或堆棧大小「非擁有」 thread
對象......但至少GCC不支持這樣做。