Skip to content

Instantly share code, notes, and snippets.

@sven-bock
Last active December 18, 2023 14:02
Show Gist options
  • Save sven-bock/819f51bffa5542f48af87fabffd1821e to your computer and use it in GitHub Desktop.
Save sven-bock/819f51bffa5542f48af87fabffd1821e to your computer and use it in GitHub Desktop.
Sample how to create a boost threadpool in a class
#include <boost/asio/io_service.hpp>
#include <boost/bind.hpp>
#include <boost/thread/thread.hpp>
#include <boost/make_shared.hpp>
#include <iostream>
class Bla{
public:
void callback(std::string msg){
std::cout << msg << std::endl;
usleep(1000000);
}
Bla(){
/*
* This will start the io_service_ processing loop. All tasks
* assigned with io_service_->post() will start executing.
*/
io_service_ = boost::make_shared<boost::asio::io_service>();
work_ = boost::make_shared<boost::asio::io_service::work>(*io_service_);
/*
* This will add 2 threads to the thread pool. (You could just put it in a for loop)
*/
std::size_t my_thread_count = 2;
for (std::size_t i = 0; i < my_thread_count; ++i){
threadpool_.create_thread(boost::bind(&boost::asio::io_service::run, io_service_));
}
};
void run(){
/*
* This will assign tasks to the thread pool.
* More about boost::bind: "http://www.boost.org/doc/libs/1_54_0/libs/bind/bind.html#with_functions"
*/
io_service_->post(boost::bind(&Bla::callback,this, "Hello World!"));
io_service_->post(boost::bind(&Bla::callback,this, "./cache"));
io_service_->post(boost::bind(&Bla::callback,this, "twitter,gmail,facebook,tumblr,reddit"));
};
void stop(){
/*
* This will stop the io_service_ processing loop. Any tasks
* you add behind this point will not execute.
*/
io_service_->stop();
/*
* Will wait till all the threads in the thread pool are finished with
* their assigned tasks and 'join' them. Just assume the threads inside
* the threadpool_ will be destroyed by this method.
*/
threadpool_.join_all();
};
private:
/*
* Create an asio::io_service and a thread_group (through pool in essence)
*/
boost::shared_ptr<boost::asio::io_service> io_service_;
boost::shared_ptr<boost::asio::io_service::work> work_;
boost::thread_group threadpool_;
};
int main(int argc, char **argv){
Bla b;
b.callback("test");
b.run();
usleep(3000000);
b.stop();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment