C++ Thread多執行緒的一個小問題
阿新 • • 發佈:2021-02-08
技術標籤:c++
問題:
std::thread::thread(const std::thread&):嘗試引用已刪除的函式
#include <iostream>
#include<thread>
#include<vector>
#include<algorithm>
#include<functional>
using namespace std;
void func()
{
cout << "from func: "<<this_thread::get_id ()<< endl;
}
int main()
{
thread::id master_id;
cout << "master id " << master_id<<endl;
cout << "max num of thread the system support : " << thread::hardware_concurrency << endl;
vector<thread> threads;
thread t1(func);
thread t2 (func);
thread t3(func);
thread t4(func);
// 這裡有個問題一定要注意,Thread 的拷貝建構函式定義成了delete的。就不能直接被訪問,所以只能使用move來創造出一個臨時的變數來填充vector
threads.push_back(move(t1));
threads.push_back(move(t2));
threads.push_back(move(t3));
threads.push_back(move(t4));
std::for_each(threads.begin(), threads.end(), std::mem_fn (&std::thread::join));
}