线程作为类的成员变量
Thread as member variable of class
我想在某个类的成员变量中保存一个线程。以下代码片段显示了我想要实现的目标:
#include <iostream>
#include <thread>
#include <vector>
class Test {
public:
std::thread& t;
Test(std::thread&& rt) : t(rt) {}
};
int main()
{
std::vector<Test> tests;
{
std::thread t ([]{
std::cout << 1;
});
tests.push_back(Test(std::move(t)));
}
for(Test mytest : tests)
{
mytest.t.join();
}
}
代码将在 join() 行处中断。错误是:
terminate called without an active exception
Aborted (core dumped)
为什么当原始线程创建的范围离开时,我不能通过 mytest.t 调用线程?
由于 std::thread 是可移动的,但不可复制,你可以这样做:
class Test {
public:
std::thread t;
Test(std::thread&& rt) : t(std::move(rt)) {}
};
int main()
{
std::vector<Test> tests;
{
std::thread t([] {
std::cout << 1;
});
tests.push_back(Test(std::move(t)));
}
for (Test& mytest : tests)
{
mytest.t.join();
}
}
在你的类中,你有一个对线程的引用,而不是一个线程对象:
std::thread& t;
^
这意味着将发生以下顺序:
{
std::thread t ([]{
std::cout << 1;
}); // 1. Thread is created.
tests.push_back(Test(std::move(t))); // 2. Reference to moved thread is taken
// and after move thread is destroyed.
// 3. Now the thread is destroyed,
// but not joined which will call `std::terminate`
// (Thanks @tkausl)
}
如果你让你的班级std::thread t
移动将起作用。
正如 @tkausl 提到的,它是一个引用,一旦线程对象超出范围并且您的引用不再有效,{}
就会销毁该对象。此外,您需要修改循环,使其不会创建原始Test
对象的副本。修改后,这将变为:
class Test {
public:
std::thread& t;
Test(std::thread&& rt) : t(rt) {}
};
int main()
{
std::vector<Test> tests;
std::thread t ([]{
std::cout << 1;
});
tests.push_back(Test(std::move(t)));
for(Test& mytest : tests)
{
mytest.t.join();
}
}
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 将包含C样式数组的对象初始化为成员变量(C++)
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 在循环中按顺序遍历成员变量
- c++类声明时,相同的例程,不同的成员变量类型
- 如何从另一个文件继承私有成员变量和公共函数
- 在C++类中,是否必须初始化作为数组的成员变量
- 如何从子成员函数修改父公共成员变量
- 我可以在 C++ 中将数据成员/变量从其定义之外添加到结构中吗?
- 从私有成员变量的成员方法返回unique_ptr
- 在派生类中使用基类的私有成员变量的最佳方法
- 静态 constexpr 类成员变量对多线程读取是否安全?
- C++:是否可以使用非静态成员变量模板?
- 打印所有继承的类成员变量和方法
- 如何在复杂继承中访问静态成员变量
- 为什么我不能在返回 const 的布尔函数中为类成员变量赋值?C++
- 成员变量与函数概念检查