Boost logo

Boost Users :

Subject: Re: [Boost-users] [asio] posting a function to an io_service object
From: Igor R (boost.lists_at_[hidden])
Date: 2009-12-28 16:32:09


> My problem is with the function that is to be executed last: how can I wait for that to be executed before stopping the io_service and joining the thread?

Usually you don't have to stop io_service explicitly - when it runs
out of work, it stops by its own. So if all you need is to perform
several functions/functors on io_service thread - just post them to
io_service, and join io_service thread(s):

// pseudo-code!
{
  asio::io_service io;
  io_.post(functor1);
  io_.post(functor2);
  thread t(&io_service::run, &io);
  t.join(); // when io_service runs out of jobs, run() exits.
}

If you need to get more control over io_service::run "lifetime", you
can use work object, like in your example:

// pseudo-code!
{
  asio::io_service io;
  shared_ptr<io_service::work> work(new io_service::work(ios));
  thread t(&io_service::run, &io);
  io_.post(functor1);
  io_.post(functor2);
  // do something...
  // when there's not more real work, and all the copies of "work"
shared ptr are reset, io_service::run will exit
  t.join();
}

If you still need to get synchronized with one of your functors being
executed in another thread, use boost::condition_variable (the functor
sets condition, main thread waits for condition):

http://www.boost.org/doc/libs/1_41_0/doc/html/thread/synchronization.html#thread.synchronization.condvar_ref.condition_variable


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net