在C++ 11呼叫C++ 11個線程:如何啓動線程,並單獨檢查其完成?
my_thread.join();
運行線程,並等待其完成。我需要首先運行線程,稍後再等待完成。它的完成,比如,在UNIX系統的方式:
pthread_create(...)
運行一個線程,
pthread_join(...)
等待完成。這可能與C + + 11?
在C++ 11呼叫C++ 11個線程:如何啓動線程,並單獨檢查其完成?
my_thread.join();
運行線程,並等待其完成。我需要首先運行線程,稍後再等待完成。它的完成,比如,在UNIX系統的方式:
pthread_create(...)
運行一個線程,
pthread_join(...)
等待完成。這可能與C + + 11?
std::thread::join()
不使線程運行。當std::thread
對象使用函數對象參數構造時,線程運行。
例如:
std::thread thrd1(doSomething); // Thread starts
// Some codes...
thrd1.join(); // Wait for thread exit
std::thread thrd2; // default constructor
thrd2 = std::thread(doSomething);
// blablabla...
thrd2.join();
啊,對不起,你是對的。 –
好,C++11
線程實際上(據我所知)使用系統主線程設施,用於UNIX系統,它可能會使用POSIX線程。
做的一個簡單的例子,我覺得你想要做的可能是這樣的:
#include <thread>
#include <iostream>
// The function run from the thread i.e. "run the thread" part of your question.
void things_to_do_in_thread() {
std::cout << "Hello World" << std::endl;
}
int main() {
// This create the thread and call the function
std::thread my_thread(things_to_do_in_thread);
//Join with the main thread
my_thread.join();
return 0;
}
你也可以給一個lambda-function
運行這將是這樣的:
#include <thread>
#include <iostream>
int main() {
std::thread my_thread([](){
std::cout << "Hello world" << std::this_thread::get_id() << std::endl;
});
my_thread.join();
}
我希望這是你所要求的,它會幫助你熟悉C++11
中的std
線程實現。
我很確定線程一旦完成構建'std :: thread'對象就會啓動。 – kennytm