为什么动态创建线程向量是错误的?我收到编译错误
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;
}
最佳答案
std::vector
的构造函数使用 initializer_list
要求元素是可复制构造的,因为 initializer_list
本身要求(它的底层“存储”被实现为一个复制构造的临时数组)。 std::thread
不可复制构造(此构造函数被删除)。
http://en.cppreference.com/w/cpp/utility/initializer_list
The underlying array is a temporary array, in which each element is copy-initialized...
没有解决这个问题的好方法 - 您不能一次初始化所有线程,但您可以使用(多次调用,每个线程一个 - 不幸的是):
emplace_back()
:pool.emplace_back(obj);
push_back()
带有右值:pool.push_back(thread{obj});
push_back()
与明确 move()
s:auto t = thread{obj};
pool.push_back(std::move(t));
关于multithreading - 为什么我不能像这样动态创建线程向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27167968/