[英]running std::thread not in Constructor
I want to understand how to work with std::thread
. 我想了解如何使用std::thread
。 Most of std::thread
tutorials looks like that 大多数std::thread
教程看起来像这样
void foo() { ... }
....
std::thread thread(foo);
....
thread.join();
Ok, I understand that we can specify which function attached to thread in constructor. 好的,我知道我们可以指定构造函数中附加到线程的函数。 But, do we have any other way? 但是,我们还有其他方法吗?
In other words, what I need to insert to run t3
thread? 换句话说,我需要插入什么来运行t3
线程?
#include <thread>
#include <iostream>
void print(const char* s){
while (true)
std::cout << s <<'\n';
}
int main() {
std::thread t1(print, "foo");
std::thread *t2;
t2 = new std::thread(print, "bar");
std::thread t3; // Don't change this line
// what I need to put here to run t3 ?
t1.join();
t2->join();
t3.join();
delete t2;
return 0;
}
t3
is essentially a dummy thread. t3
本质上是虚拟线程。 Looking at the reference the default constructor says: 查看参考,默认的构造函数说:
Creates new thread object which does not represent a thread. 创建不代表线程的新线程对象。
But since std::thread
has operator=(std::thread&&)
you can make it represent an actual thread by moving a new thread into the variable: 但是由于std::thread
具有operator=(std::thread&&)
您可以通过将新线程移入变量来使其代表实际线程:
t3 = std::thread(print, "foobar");
This will create and launch a new thread, then assign it to t3
. 这将创建并启动一个新线程,然后将其分配给t3
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.