I have a class which maintains a worker thread. It needs to be move constructible as I pass them around and add/remove from arrays, such as:
for (...) {
Foo foo;
foos.push_back(std::move(foo));
}
The class setup looks like this:
Foo::Foo() : worker(), working(true) {
worker = std::thread(&Foo::work, this);
}
Foo::Foo(Foo &&foo) {
working = true;
worker = std::move(foo.worker);
}
Foo::~Foo() {
if (worker.joinable()) {
working = false;
worker.join();
}
}
void Foo::work() {
while(working) {
std::cout << "working..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
The problem is that after a Foo
has been moved, its worker thread exits. I discovered it's because working
is now seen by the worker
to be false
.
How can I get the worker
thread to see the instance variables of the new (moved-to) parent Foo
object? Is this possible? Is my move constructor totally wrong?