how a thread can signal when it's finished?

Posted by Kyle on Stack Overflow See other posts from Stack Overflow or by Kyle
Published on 2010-05-28T00:09:05Z Indexed on 2010/05/28 0:11 UTC
Read the original article Hit count: 118

Filed under:
|
|
|
#include <iostream>
#include <boost/thread.hpp>
using std::endl; using std::cout;
using namespace boost;


mutex running_mutex;

struct dostuff
{
    volatile bool running;
    dostuff() : running(true) {}
    void operator()(int x)
    {
        cout << "dostuff beginning " << x << endl;
        this_thread::sleep(posix_time::seconds(2));
        cout << "dostuff is done doing stuff" << endl;
        mutex::scoped_lock running_lock(running_mutex);
        running = false;
    }
};

bool is_running(dostuff& doer)
{
    mutex::scoped_lock running_lock(running_mutex);
    return doer.running;
}

int main()
{
    cout << "Begin.." << endl;
    dostuff doer;
    thread t(doer, 4);

    if (is_running(doer)) cout << "Cool, it's running.\n";

    this_thread::sleep(posix_time::seconds(3));

    if (!is_running(doer)) cout << "Cool, it's done now.\n";
    else cout << "still running? why\n"; // This happens! :(

    return 0;
}

Why is the output of the above program:

Begin..
Cool, it's running.
dostuff beginning 4
dostuff is done doing stuff
still running? why

How can dostuff correctly flag when it is done? I do not want to sit around waiting for it, I just want to be notified when it's done.

© Stack Overflow or respective owner

Related posts about c++

Related posts about multithreading