包含 std::threads 的元素向量
Vector of elements containing std::threads
我有一个类Tester
包含一个std:thread
对象和一个Tester
std::vector
。我知道我无法复制线程,所以push_back
是不可能的,但是为什么emplace_back
不起作用?代码中的副本在哪里?
#include <iostream>
#include <thread>
#include <vector>
#include <functional>
#include <unistd.h>
class Tester
{
public:
Tester(std::function<void(void)> func) :
th(func)
{
}
~Tester()
{
th.join()
}
private:
std::thread th;
};
std::vector<Tester> testers;
void InnerHelloWorld()
{
std::cout << "Hello from the inner word!n";
}
int main() {
std::cout << "Hello World!n";
for(size_t i = 0 ; i < 4 ; i++)
{
testers.emplace_back(InnerHelloWorld);
}
sleep(1);
return 0;
}
代码中有几个小问题
您错过了以下项的尾随分号:
th.join()
但重要的是,你需要给你的类一个移动构造函数 - 默认的很好:
Tester(Tester&&) = default;
这是必需的,因为当向量调整自身大小时,它们需要移动或复制其元素。通常会为您创建一个移动构造函数,但在您的情况下,使用自定义析构函数会抑制它。看这里。
这将允许代码编译,但随后会在运行时引发异常。这是因为您有时会从移自Testers
中析构,这会在移自线程上调用 join。幸运的是,这是一个简单的解决方法:
~Tester()
{
if(th.joinable())
th.join();
}
完整工作代码:
#include <iostream>
#include <thread>
#include <vector>
#include <functional>
#include <unistd.h>
class Tester
{
public:
Tester(std::function<void(void)> func) :
th(func)
{
}
~Tester()
{
if(th.joinable())
th.join();
}
Tester(Tester&&) = default;
private:
std::thread th;
};
std::vector<Tester> testers;
void InnerHelloWorld()
{
std::cout << "Hello from the inner word!n";
}
int main() {
std::cout << "Hello World!n";
for(size_t i = 0 ; i < 4 ; i++)
{
testers.emplace_back(InnerHelloWorld);
}
sleep(1);
return 0;
}
你需要为你的类定义移动构造函数,以便它变得MoveInsertable并满足emplace
方法的要求:
Tester(Tester && other) :
th(::std::move(other.th))
{
}
修复缺少移动构造函数后会出现的另一个问题是尝试加入不可连接的线程,因为实际线程可能已被移动到另一个对象中。所以你需要添加一个相应的检查:
~Tester()
{
if(th.joinable())
{
th.join();
}
}
相关文章:
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- C++:如何循环通过向量中的整数元素
- 如何在C++向量中奇数元素前面加上值-1,我在使用insert函数时遇到了问题
- 不允许在向量中添加更多元素
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- 使用并行参数向量调用元素向量的成员函数
- C++ 查找字符串中存在的元素向量
- 包含 std::threads 的元素向量
- 避免从单一元素向量转换为基元类型
- 对自定义元素向量进行排序时出现意外(至少对我来说)行为
- 如何为对元素(向量和int)配对创建unique_ptr也是unique_ptr
- 元素向量乘法 C++(代码不起作用)
- 时间和空间复杂性在二叉树的每个级别创建元素向量(NON-BST)
- 遍历结构元素向量
- 犰狳C++中的元素向量或矩阵乘法
- 为什么'std::vector<int> b{2};'创建 1 元素向量,而不是 2 元素向量?
- 可移动元素向量的大小调整是否有效?
- 唯一元素向量的c++模板函数
- 获取索引和元素-向量问题
- 定义一个生成元素向量的函数时,正确的方法是什么?