io_service::stop()
causes all invocations of run()
or run_one()
to return as soon as possible. It does not remove any outstanding handlers that are already queued into the io_service
. When io_service::stop()
is invoked, the threads in threadpool
will return as soon as possible, causing each thread of execution to be complete.
As io_service::post()
will return immediately after requesting that the io_service
invoke the handler, it is non-deterministic as to how many posted handlers will be invoked by threads in threadpool
before the io_service
is stopped.
If you wish for thread_func
to be invoked ls1
times, then one simple alternative is to reorganize the code so that work is added to the io_service
before the threadpool
services it, and then the application lets the io_service
run to completion.
boost::asio::io_service ioService;
// Add work to ioService.
for (unsigned i = 0; i < ls1; i++)
{
ioService.post(boost::bind(
&thread_func,i, rs1, rs2, ls2, arr, left_arr, &result));
}
// Now that the ioService has work, use a pool of threads to service it.
boost::thread_group threadpool;
for (unsigned t = 0; t < num_threads; t++)
{
threadpool.create_thread(boost::bind(
&boost::asio::io_service::run, &ioService));
}
// Once all work has been completed (thread_func invoked ls1 times), the
// threads in the threadpool will be completed and can be joined.
threadpool.join_all();