【发布时间】:2020-08-06 20:49:34
【问题描述】:
标题很容易解释。我正在尝试获得一个线程保护的最小工作示例,它还可以支持 std::threads 具有的移动语义。
#include <iostream>
#include <thread>
#include <vector>
#include <functional>
class ThreadGuard {
public:
explicit ThreadGuard(std::thread input): t(std::move(input))
{}
~ThreadGuard(){
if(t.joinable()){
t.join();
}
}
ThreadGuard(ThreadGuard const& t) = delete;
ThreadGuard& operator=(ThreadGuard const&) = delete;
ThreadGuard& operator=(ThreadGuard&& out){
this->t = out.transfer();
return *this;
}
std::thread transfer(){
return std::move(t);
}
private:
std::thread t;
};
void doWork(std::string input){
std::cout << input << std::endl;
}
static const auto numThreads = 4;
int main()
{
std::vector<ThreadGuard> tp;
tp.reserve(numThreads);
for(auto i = 0 ; i < numThreads; ++i){
tp[i] = ThreadGuard(std::thread(doWork, i));
}
return 0;
}
目前遇到了障碍。 std::invoke,没有找到匹配的重载函数,我看不到这里缺少什么。
【问题讨论】:
标签: c++ multithreading parallel-processing