0

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?

Dan Halliday
  • 725
  • 6
  • 22
  • Well, you're getting Foo destructor called, aren't you? – Severin Pappadeux May 06 '15 at 22:42
  • Basically, on move you should render `foo` into some inoperable state, so destructor won't do anything – Severin Pappadeux May 06 '15 at 22:43
  • You're binding the thread to a specific instance by passing `this` as an argument and calling a member function of that particular object. Therefore, moving the thread won't be as trivial as moving its handle. – dyp May 06 '15 at 22:43
  • You can move the thread to a new object but isn't the `this` pointer the thread was constructed with still pointing to the old object? – Galik May 06 '15 at 22:43
  • A very easy solution is to put the whole state including the thread in an object on the heap, and storing only a `unique_ptr` to that in `Foo`. – dyp May 06 '15 at 22:46
  • Your thread is basically running one of the methods of a specific object. You can't just magically have it start running the same method of a different object. – Galik May 06 '15 at 22:46

0 Answers0