Boost logo

Boost Users :

Subject: Re: [Boost-users] single thread in loop
From: Igor R (boost.lists_at_[hidden])
Date: 2013-07-02 02:09:56


> I'm using boost 1.53 on windows 7. I have a main loop which runs some checks
> and when events are received, results in callbacks that add tasks onto a
> queue. I then pull a task off the queue, wish to start a thread (and only
> one thread) to handle the task, and continue to loop checking for certain
> events. And each time I go through the loop, I want to check to see if the
> current thread has completed before pulling off another task to process.
>
> My problem is that I'm not sure how to write the thread in to do this and
> not join because I have to keep looping to check for certain events.

You can use timed_join, as in your example, but note that the thread
might exit anytime.
Instead of complicated management of tasks and threads, why would't
you use asio::io_service? Just run it in 1 thread, and post your tasks
to it. When io_service doesn't have any "active" work, its thread
would be idle.

//setup io_serivce before the loop
asio::io_service io_service;
// give it some "work", to prevent premature exit
shared_ptr<asio::io_service::work> work(new asio::io_service::work(io_service));
boost::thread t(&asio::io_service::run, &io_service);
t.detach();
//...
// from within your loop, post tasks
io_service.post(yourFunctor); // yourFunctor will be executed in the
separate thread


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