在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