Multithreading C++;11个线程:如何启动一个线程,并分别检查其完成情况?
在C++11中,调用Multithreading C++;11个线程:如何启动一个线程,并分别检查其完成情况?,multithreading,c++11,Multithreading,C++11,在C++11中,调用 my_thread.join(); 运行线程并等待其完成。我需要,首先,运行线程,然后,等待它的完成。例如,在UNIX系统中的操作方式: pthread_create(...) 运行一个线程,然后 pthread_join(...) 等待完成。这在C++11中可能吗?std::thread::join()不会使线程运行。当std::thread使用函数对象参数构造对象时,线程运行 例如: std::thread thrd1(doSomething); // Threa
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;
}
我希望这就是您所要求的,并且它将帮助您熟悉
C++11
中的std
线程实现。我确信,只要您完成了std::thread
对象的构建,线程就会启动。
#include <thread>
#include <iostream>
int main() {
std::thread my_thread([](){
std::cout << "Hello world" << std::this_thread::get_id() << std::endl;
});
my_thread.join();
}