Last active
August 29, 2015 14:18
-
-
Save joefutrelle/4dbdbdcd11205bef0d8c to your computer and use it in GitHub Desktop.
Simple Boost ASIO based parallelization template
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <boost/thread.hpp> | |
#include <boost/asio.hpp> | |
#define N_THREADS 4 | |
#define N_JOBS 10 | |
/* compile on Ubuntu using | |
g++ par.cpp -lboost_thread -lboost_system | |
must have installed libboost-dev libboost-thread-dev | |
*/ | |
// simple task callback | |
void print_task(int n) { | |
std::cout << "job " << n << " running" << std::endl; | |
} | |
int main(int argc, char **argv) { | |
// create io service | |
boost::asio::io_service io_service; | |
// use the work object to keep threads alive before jobs are posted | |
std::auto_ptr<boost::asio::io_service::work> work(new boost::asio::io_service::work(io_service)); | |
// create and populate the thread pool with worker threads | |
boost::thread_group workers; | |
for(int i = 0; i < N_THREADS; i++) { | |
workers.create_thread(boost::bind(&boost::asio::io_service::run, &io_service)); | |
} | |
std::cout << "queueing jobs" << std::endl; | |
// now post jobs | |
for(int i = 0; i < N_JOBS; i++) { | |
io_service.post(boost::bind(print_task, i)); | |
std::cout << "queued job " << i << std::endl; | |
} | |
// destroy the work object to indicate that there are no more jobs | |
work.reset(); | |
// now wait for all running jobs to complete | |
workers.join_all(); | |
// at this point all work is done | |
std::cout << "all jobs complete" << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment