$include_dir="/home/hyper-archives/boost-users/include"; include("$include_dir/msg-header.inc") ?>
Subject: [Boost-users] asio::io_service as a thread-pool executor
From: aiooua (aiooua_at_[hidden])
Date: 2011-09-08 18:50:07
I'm trying to use boost::asio::io_service as a thread pool executor.
Here's my attempt:
----
using std::vector;
using boost::bind;
using boost::thread;
using boost::shared_ptr;
using boost::asio::io_service;
class executor
{
public:
executor(size_t n): service_(n), work_(service_)
{
for (size_t i = 0; i < n; i++)
{
shared_ptr<thread> worker(new thread(bind(&io_service::run,
&service_)));
pool_.push_back(worker);
}
}
~executor()
{
service_.stop();
for (auto i = pool_.begin(); i != pool_.end(); ++i)
{
(*i)->join();
}
}
template<typename F> void submit(F task)
{
service_.post(task);
}
private:
io_service service_;
io_service::work work_;
vector<shared_ptr<thread> > pool_;
};
void work() {}
void other_work(const char *c) {}
struct functor_work { void operator()() {} };
auto lambda = [] {};
int main()
{
executor e(4);
e.submit(work);
e.submit(boost::bind(other_work, "input"));
e.submit(functor_work());
e.submit(lambda);
}
----
Is this usage correct or am I missing anything here? The bit I'm not
sure about in particular is this:
Is it guaranteed that the io_service::run will wait for the completion
of the posted jobs (via io_service::post) after I have called
io_service::stop? In other words, do I have to explicitly ensure that
my executor instance lives at least as long as the last submitted job
has finished? Or can I assume that io_service::run will only return
after all its posted jobs have had a chance to finish?
Thanks!