[英]running std::thread not in Constructor
我想了解如何使用std::thread
。 大多數std::thread
教程看起來像這樣
void foo() { ... }
....
std::thread thread(foo);
....
thread.join();
好的,我知道我們可以指定構造函數中附加到線程的函數。 但是,我們還有其他方法嗎?
換句話說,我需要插入什么來運行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
本質上是虛擬線程。 查看參考,默認的構造函數說:
創建不代表線程的新線程對象。
但是由於std::thread
具有operator=(std::thread&&)
您可以通過將新線程移入變量來使其代表實際線程:
t3 = std::thread(print, "foobar");
這將創建並啟動一個新線程,然后將其分配給t3
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.