Ern*_*own 8 c++ multithreading c++11
我有一个类Tester包含std:thread的对象,和std::vector的Tester.我明白我不能复制线程,所以这是不可能的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;
}
Run Code Online (Sandbox Code Playgroud)
Mik*_*ine 15
您的代码中存在一些小问题
你错过了以下的尾随分号:
th.join()
Run Code Online (Sandbox Code Playgroud)
但重要的是,你需要给你的类一个移动构造函数 - 默认的是:
Tester(Tester&&) = default;
Run Code Online (Sandbox Code Playgroud)
这是必需的,因为当向量调整大小时,他们需要移动或复制它们的元素.通常会为您创建移动构造函数,但在您的情况下,使用自定义析构函数会对其进行压缩.看到这里.
这将让你的代码编译,但它会在运行时抛出异常.这是因为你有时会从移动的Testers线程中解析,从移动线程调用连接.幸运的是,这是一个简单的修复:
~Tester()
{
if(th.joinable())
th.join();
}
Run Code Online (Sandbox Code Playgroud)
完整的工作代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)