Asio & strand & threads
Hi Boosters,
I'm trying to figure out how Asio's strand works.
My concept of strand is a bit blurry.
Asio's Timer.5 tutorial says:
"An boost::asio::strandhttp://asio.sourceforge.net/boost_asio_0_3_7/libs/asio/doc/reference/a00260....guarantees
that, for those handlers that are dispatched through it, an
executing handler will be allowed to complete before the next one is
started. This is guaranteed irrespective of the number of threads that are
calling boost::asio::io_service::run()http://asio.sourceforge.net/boost_asio_0_3_7/libs/asio/doc/reference/a00139.....
Of course, the handlers may still execute concurrently with other handlers
that were *not* dispatched through an
boost::asio::strandhttp://asio.sourceforge.net/boost_asio_0_3_7/libs/asio/doc/reference/a00260....,
or were dispatched through a different
boost::asio::strandhttp://asio.sourceforge.net/boost_asio_0_3_7/libs/asio/doc/reference/a00260....object."
Asio's documentation for boost::asio::io_service::run says:
"Run the io_service's event processing loop.
The run()http://asio.sourceforge.net/boost_asio_0_3_7/libs/asio/doc/reference/a00139....function
blocks until all work has finished and there are no more handlers
to be dispatched, or until the
io_servicehttp://asio.sourceforge.net/boost_asio_0_3_7/libs/asio/doc/reference/a00139....has
been interrupted.
Multiple threads may call the
run()http://asio.sourceforge.net/boost_asio_0_3_7/libs/asio/doc/reference/a00139....function
to set up a pool of threads from which the
io_servicehttp://asio.sourceforge.net/boost_asio_0_3_7/libs/asio/doc/reference/a00139....may
execute handlers."
The key here is "Multiple threads may call the
run()http://asio.sourceforge.net/boost_asio_0_3_7/libs/asio/doc/reference/a00139....function
to set up a pool of threads from which the
io_servicehttp://asio.sourceforge.net/boost_asio_0_3_7/libs/asio/doc/reference/a00139....may
execute handlers." --
This implies to me that it's automatic, and the thread pool will take
whatever work it can.
I've created a little example which has ten threads calling io_service::run,
and printing out which thread is calling a handler given to the deadline
timer.
The issue here is that when I run this Test, the same thread is calling
print() every time, no matter what I do.
My understanding of this Test is as so:
io_service holds a queue of asynchronous events.
You fill up the io service with events, and then you call run on it.
If multiple threads call run, they'll do whatever work they can.
I'm calling run from 10 threads:
Each thread will see what events are there, and handle them if possible.
The asynchronous waits are calling a strand wrapper.
The strand wrapper is like a mutex, and ensures that no two threads will
call print() at the same time.
What is going on, and why is the same thread calling print() every time?
Is my understanding here completely wrong?
- Zola
// The Test:
#include <iostream>
#include
participants (1)
-
Zola