Boost logo

Boost Users :

Subject: Re: [Boost-users] [Threads] How to keep number of running thread constant, performing different operations
From: Lars Viklund (zao_at_[hidden])
Date: 2011-06-17 06:39:05


On Fri, Jun 17, 2011 at 12:20:31PM +0200, Ovanes Markarian wrote:
> On Fri, Jun 17, 2011 at 11:10 AM, Lars Viklund <zao_at_[hidden]> wrote:
>
> > On Fri, Jun 17, 2011 at 10:12:47AM +0200, Ovanes Markarian wrote:
> > > On Fri, Jun 17, 2011 at 9:05 AM, Alessandro Candini <candini_at_[hidden]>
> > wrote:
> > [...]
> >
> > For managing the N threads, you can use a thread_group.
>
>
> Yes, but than you must implement and debug your own thread pool pattern.
> Thread group only creates a number of threads, but you need to implement the
> producer/consumer problem to retrieve work tasks from each thread from the
> queue. Now there is a choise to either use a ready thread pool or implement
> it yourself... AFAIK Boost has no official thread pool
> implementation, which is not in internal impl namespace and guarantees the
> interface.

We have thread_group, we have Asio. One needs nothing else. I think
you're misunderstanding what I suggested.

I do not consider doing this remotely bothersome, particularly as you
only need features present in Boost itself.

It should need no debugging, as it's practically impossible to get
wrong. If you for some reason need completion notifications from your
workers, have that as part of your task, or wrap your functor in
something.

---8<---
asio::io_service io;
scoped_ptr<asio::io_service::work> work(new asio::io_service::work(io));

boost::thread_group tg;
auto N = boost::thread::hardware_concurrency();

for (unsigned i = 0; i < N; ++i)
  tg.create_thread(boost::bind(&asio::io_service::run, boost::ref(io));

io.post(some_task);
io.post(some_other_task);

// invoke io.post whenever you want to enqueue something.

// time passes, shutdown time has arrived

work.reset();
tg.join_all();
---8<---

-- 
Lars Viklund | zao_at_[hidden]

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net