我正在尝试扩展一些人在这里帮助我的内容Call function inside a lambda pass to a thread所以我的工作类可以支持 move 构造函数和 move operator=
,但我的问题是我的类是this
通过复制(或引用)绑定的) 到线程,以便它可以访问类值。其中有几个atomic<bool>
,一个condition_variable
和一个mutex
。
但是当我尝试移动它时,因为线程绑定到另一个条件变量mutex
和atomic
s,我对它所做的任何事情都不起作用。我怎样才能解决这个问题?我是否需要使用更复杂的对象并移动它而不是 lambda,以便线程可以引用它?还是有其他选择。一如既往的帮助将不胜感激:)。
这是实现的片段(MWE)。
class worker {
public:
template <class Fn, class... Args>
explicit worker(Fn func, Args... args) {
t = std::thread(
[&func, this](Args... cargs) -> void {
std::unique_lock<std::mutex> lock(mtx);
while (true) {
cond.wait(lock, [&]() -> bool { return ready; });
if (terminate)
break;
func(cargs...);
ready = false;
}
},
std::move(args)...);
}
worker(worker &&w) : t(std::move(w.t)) { /* here there is trouble */ }
worker &operator=(worker &&w) {
t = std::move(w.t);
terminate.store(wt.terminate);
ready.store(wt.ready);
return *this;
/* here too */
}
~worker() {
terminate = true;
if (t.joinable()) {
run_once();
t.join();
}
}
worker() {}
void run_once() {
std::unique_lock<std::mutex> lock(mtx);
ready = true;
cond.notify_one();
}
bool done() { return !ready; }
private:
std::thread t;
std::atomic<bool> ready, terminate; // What can I do with all these?
std::mutex mtx; //
std::condition_variable cond; //
};
int main() {
worker t;
t = worker([]() -> void { cout << "Woof" << endl; });
t.run_once();
while(!t.done()) ;
return 0;
}
对不起,代码的大转储。