Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 2

Using boost::threadpool with boost::future

Here is a small C++ function which allows you to submit async jobs into the thread pool and
track their execution status using the concept of futures:
#include
#include
#include
#include

"boost/threadpool.hpp"
"boost/future.hpp"
"boost/utility/result_of.hpp"
"boost/shared_ptr.hpp"

template<typename Thp, typename Func>


boost::shared_future< typename boost::result_of<Func()>::type >
submit_job(Thp& thp, Func f)
{
typedef typename boost::result_of<Func()>::type result;
typedef boost::packaged_task<result> packaged_task;
typedef boost::shared_ptr<boost::packaged_task<result> >
packaged_task_ptr;
packaged_task_ptr task(new packaged_task(f));
boost::shared_future<result> res(task->get_future());
boost::threadpool::schedule(thp, boost::bind(&packaged_task::operator(),
task));
}

return res;

A typical example of its possible usage:


User lookup_user_in_database(int id) { ... }
...
int main()
{
boost::threadpool::pool thp(3);//number of threads
boost::shared_future<User> future =
submit_job(boost::bind(lookup_user_in_database, 10));
while(!future.is_ready())
{
//do something useful
}
User = future.get();
...
}

boost::futures are now finally officially shipped with boost starting with 1.41 release.
boost::threadpool is not yet an official boost library, however you can find it here.
Much kudos to authors of these amazing libraries!
This entry was posted on Thursday, December 10th, 2009 at 12:18 am and is filed under async, multicore, boost,
c++. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback
from your own site.

2 Responses to Using boost::threadpool with boost::future

1. Denis Bazhenov Says:


December 10th, 2009 at 3:45 am

Conception of Futures very popular on Java Platform also. But there is one thing that
Im missing in Futures - asynchronous completition. Sometimes there is no need to
wait for task to complete. All I need is to give task and completition function to thread
pool. For example:
Callable task = new LoadUserTask(userId);
executor.submit(task, new CompletionHandler {
public void onComplete(User user) {
user.setLastLoginTime(now());
}
});

Is there something similar in C++?

You might also like