views:

2165

answers:

1

I have this code for a custom class 'sau_timer':

sau_timer::sau_timer(int secs, timerparam f, vector<string> params) : strnd(io), 
    t(io, boost::posix_time::seconds(secs))
{
    assert(secs > 0);
    this->f = f;
    this->params = params;
    t.async_wait(strnd.wrap(boost::bind(&sau_timer::exec, this, _1)));
    boost::thread thrd(boost::bind(&boost::asio::io_service::run, &io));
    io.run();
}

void sau_timer::exec(const boost::system::error_code&) {
    (f)(params);
}

I want it so that when I make a sau_timer object, the timer will start, but allow program execution to continue. For example, this is main():

int main(int argc, char* argv[])
{
    vector<string> args(1);
    args[0] = "Hello!";
    sau_timer timer_test(3, sau_prompt, args);
    args[0] = "First!";
    sau_prompt(args);
    timer_test.thrd.join();
    return 0;
}

My intention here is that timer_test is made, starting a timer that waits three seconds before calling sau_prompt("Hello!"), but that sau_prompt("First!") will be called first. At the moment, Hello is shown in the prompt before First, indicating that the timer is halting the entire program for three seconds before allowing it to continue. I want the timer to run in the background.

What am I doing wrong? The code compiles...

Thank you.

+4  A: 
Beh Tou Cheh
I put timer_test.io.run(); under the line sau_timer timer_test(3, sau_prompt, args); in main(), and removed the io.run() from the class constructor, but the effect is still the same. I fear I've misunderstood?
Motig
The example code should be enough for you to understand how asio should be used in general. You see the idea is not to create threads to run is objects say a timer or a reciever object, but rather to create multiple threads that run io_services, and to let those threaded io_services run async calls in a threaded/concurrent manner.
Beh Tou Cheh