Skip to content

Instantly share code, notes, and snippets.

@autosquid
Created October 21, 2014 06:11
Show Gist options
  • Save autosquid/c5e5b3964524130d1c4d to your computer and use it in GitHub Desktop.
Save autosquid/c5e5b3964524130d1c4d to your computer and use it in GitHub Desktop.
ThreadPool with boost thread and asio
namespace bamthread
{
typedef std::unique_ptr<boost::asio::io_service::work> asio_worker;
// the actual thread pool
struct ThreadPool {
ThreadPool(size_t threads) :service(), working(new asio_worker::element_type(service)) {
for ( std::size_t i = 0; i < threads; ++i ) {
auto worker = boost::bind(&boost::asio::io_service::run, &(this->service));
g.add_thread(new boost::thread(worker));
}
}
template<class F>
void enqueue(F f){
service.post(f);
}
~ThreadPool() {
working.reset(); //allow run() to exit
g.join_all();
service.stop();
}
private:
boost::asio::io_service service; //< the io_service we are wrapping
asio_worker working;
boost::thread_group g; //< need to keep track of threads so we can join them
};
}
@kliberty
Copy link

Is this code under the Apache license like your other projects?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment