I implemented a thread pool using boost::asio , and several boost::thread objects calling boost::asio::io_service::run() . However, the requirement I was given was to be able to track all topics for "health." My intention is to create a simple watch object that can be passed through the thread pool - if it passes, then we can assume that the thread is still processing the work.
However, given my implementation, I'm not sure how (if) I can reliably control all threads in the pool. I just delegated the stream function boost::asio::io_service::run() , so sending the sentinel object to the io_service instance io_service not guarantee which stream will actually receive this tell-tale and do the job.
One option might be to simply periodically insert a sentinel signal and hope that it will be picked up by each thread at least once for a reasonable amount of time, but this is obviously not ideal.
Take the following example. Due to the fact that the handler is encoded, in this case we see that each thread will do the same work, but in fact I will not control the implementation of the handler, some of them can be long, while others will be almost immediately .
#include <iostream> #include <boost/asio.hpp> #include <vector> #include <boost/thread.hpp> #include <boost/bind.hpp> void handler() { std::cout << boost::this_thread::get_id() << "\n"; boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } int main(int argc, char **argv) { boost::asio::io_service svc(3); std::unique_ptr<boost::asio::io_service::work> work(new boost::asio::io_service::work(svc)); boost::thread one(boost::bind(&boost::asio::io_service::run, &svc)); boost::thread two(boost::bind(&boost::asio::io_service::run, &svc)); boost::thread three(boost::bind(&boost::asio::io_service::run, &svc)); svc.post(handler); svc.post(handler); svc.post(handler); svc.post(handler); svc.post(handler); svc.post(handler); svc.post(handler); svc.post(handler); svc.post(handler); svc.post(handler); work.reset(); three.join(); two.join(); one.join(); return 0; }
source share