0

If I already have boost's ios service running in a separate thread like this:

boost::asio::io_service ios;
boost::thread bt(boost::bind(&boost::asio::io_service::run, &ios));

Is it possible to then use it for a socket or timer? Or does it need to be stopped before it is passed to these constructors?

boost::asio::deadline_timer dt1 = boost::asio::deadline_timer(ios);
user846566
  • 373
  • 1
  • 3
  • 12

2 Answers2

1

Yes, it has to be running for async io to work - see this answer for detailed explanation. The problem is io_service::run method returns when there is no work to do and i/o thread may just exit. The standard solution is to create io_service::work instance before starting i/o thread. Also you maybe would like to catch exceptions in background thread to prevent i/o loop termination.

Community
  • 1
  • 1
dewaffled
  • 2,850
  • 2
  • 17
  • 30
  • Yes the answer from [Tanner Sansbury](http://stackoverflow.com/users/1053968/tanner-sansbury) is a very very good introduction to boost-asio, the documentation for asio is very well made, but it is minimalist, there is always the answer to your question, but answer may be splitted. Read that answer from Tanner again and again in order to understand the asio workflow, then using asio is a joy ! – Jean Davy Oct 21 '14 at 13:36
0

io_service is threadsafe, it does not need to be stopped in order to post (more) work.

Of course, you have to make sure it is still running and keeps running as long as you want to be able to post additional work.

ioservice::work exists for that puppose.

sehe
  • 374,641
  • 47
  • 450
  • 633