Created
          October 21, 2014 06:11 
        
      - 
      
- 
        Save autosquid/c5e5b3964524130d1c4d to your computer and use it in GitHub Desktop. 
    ThreadPool with boost thread and asio
  
        
  
    
      This file contains hidden or 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
    
  
  
    
  | 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 | |
| }; | |
| } | |
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
Is this code under the Apache license like your other projects?