cpp*_*hex 6 multithreading c++11
为什么动态创建线程向量是错误的?我收到编译错误
C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\xmemory0(593):错误 C2280:'std::thread::thread(const std::thread &)':试图引用已删除的函数
其次是很多其他的东西。
#include <iostream>
#include <thread>
#include <vector>
using std::vector;
using std::thread;
using std::cout;
class obj_on_thread {
public:
void operator()()
{
std::cout << "obj on thread\n";
}
};
void function_on_thread() {
std::cout << "function on thread\n";
}
auto named_lambda = []() { std::cout << "named_lambda_on_thread\n"; };
int main(){
obj_on_thread obj;
vector<thread> pool {
thread{ obj },
thread{ function_on_thread },
thread{ named_lambda },
thread{ []() { cout << "anonymous lambda on thread\n"; } }
};
cout << "main thread\n";
for(auto& t : pool)
{
if (t.joinable())
{
cout << "Joinable = true";
t.join(); //if called must be called once.
}
else
{
cout << "this shouldn't get printed, joinable = false\n";
}
}
for (auto& t : pool)
{
if (t.joinable())
{
cout << " This won't be printed Joinable = true";
}
else
{
cout << "joinable = false thread are already joint\n";
}
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
std::vector使用的构造函数initializer_list要求元素是可复制构造的,因为initializer_list它本身要求(其底层“存储”被实现为复制构造的临时数组)。std::thread不可复制构造(此构造函数被删除)。
http://en.cppreference.com/w/cpp/utility/initializer_list
底层数组是一个临时数组,其中每个元素都被复制初始化...
没有解决这个问题的好方法 - 您不能一次初始化所有线程,但您可以使用(多次调用,每个线程一个 - 不幸的是):
emplace_back():
pool.emplace_back(obj);
Run Code Online (Sandbox Code Playgroud)push_back() 带有右值:
pool.push_back(thread{obj});
Run Code Online (Sandbox Code Playgroud)push_back()使用显式move()s:
auto t = thread{obj};
pool.push_back(std::move(t));
Run Code Online (Sandbox Code Playgroud)