1
votes

I have recently used boost::asio::strand. I am inexperienced on this.

What I have faced, if I make a call to function1 with strand::wrap() and call function2 with strand::wrap() in ~function1, function2 is waiting for completion of function1.

ioservice->post(m_strand.wrap(boost::bind( function1 )));
    ioservice->post(m_strand.wrap(boost::bind( function2 )));  

if I change change the code like this, it is working as my expectation

ioservice->post(m_strand.wrap(boost::bind( function1 )));
    ioservice->post((boost::bind( function2 )));

Is this because m_strand is queuing the function calls?

What I have found in my search;

A boost::asio::strand 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 io_service::run(). Of course, the handlers may still execute concurrently with other handlers that were not dispatched through an boost::asio::strand, or were dispatched through a different boost::asio::strandobject.

When initiating the asynchronous operations, each callback handler is wrapped using the boost::asio::strand object. The strand::wrap() function returns a new handler that automatically dispatches its contained handler through the boost::asio::strand object. By wrapping the handlers using the same boost::asio::strand, we are ensuring that they cannot execute concurrently.

What I have to do for execute function2 without waiting for function1 completion? (I know I can execute it without thread or strand, but I want to call it with strand::wrap())

1
all handlers through the same strand are serialised. use a different strand if you do not want this. You are dispatching both calls through the same strand, so therefore they are serialised. - dgsomerton
@dgsomerton Does not cause problems(about concurrency) to use different strand objects? - yunus celik

1 Answers

0
votes

Strands are explicitly designed to only allow one function at a time to execute.

If you are using asynchronous methods then when one function is waiting for an asynchronous method to return other functions will be allowed to execute on the same strand.

If you aren't using asynchronous methods then strands will simply execute the posted functions in serial as you have observed.