2012-12-16 226 views
1

我正在嘗試使用boost asio和工作隊列來創建boost線程池。但是我一直堅持,我需要一個監視功能,它應該保持運行並跟蹤隊列。我不知道該如何寫,目前我把它放在我的線程池類中。我也試圖用全局函數編寫seprate線程。有人可以提出任何建議嗎?boost boost :: asio

#include <boost/thread/thread.hpp> 
#include <boost/asio.hpp> 
#include<memory> 
#include<vector> 
#include<list> 

using namespace std; 

class threadWork 
{ 
public: 
virtual void run()=0; 
}; 

class thread_pool 
{ 
private: 
    boost::asio::io_service io_service_; 
    boost::asio::io_service::work work_; 
    boost::thread_group threads_; 
    std::size_t available_; 
    boost::mutex mutex_; 

    list<shared_ptr<threadWork>> workQueue; 

public: 


    thread_pool(std::size_t pool_size) : work_(io_service_), available_(pool_size) 
    { 
    for (std::size_t i = 0; i < pool_size; ++i) 
    { 
     threads_.create_thread(boost::bind(&boost::asio::io_service::run, &io_service_)); 
    } 
    } 


    ~thread_pool() 
    { 

    io_service_.stop(); 

try 
    { 
     threads_.join_all(); 
    } 
    catch (...) {} 
    } 

    void enqueue(shared_ptr<threadWork> work) 
    { 
    workQueue.push_back(work); 
    } 

    void keepRunning() // how to call this ? 
    { 
    while(true) 
    { 
     boost::unique_lock<boost::mutex> lock(mutex_); 

     if (0 == available_) // If no threads are available, then sleep. 
     { 
      boost::this_thread::sleep(boost::posix_time::milliseconds(1000)); 
     } 
     else 
     { 

      if(workQueue.empty() != true) 
      { 
       --available_; 
       io_service_.post(boost::bin(&thread_pool::wrap_task,this , workQueue)); 
       workQueue.pop_front(); 
      } 
     } 
    } 
    } 

private: 

    void wrap_task(list<shared_ptr<threadWork>>& workQueue) 
    { 
    try 
    { 
    workQueue.front()->run(); // Run the user supplied task. 
    } 

catch (...) // Suppress all exceptions. 
{ 

} 

boost::unique_lock<boost::mutex> lock(mutex_); 
    ++available_; 
    } 
}; 

class someWork:public threadWork 
{ 
public: 
virtual void run() 
{ 
    cout<<"some long task \n"; 
    boost::this_thread::sleep(boost::posix_time::milliseconds(5000)); 
} 
}; 

int main() 
{ 

thread_pool pool(10); 

pool.keepRunning(); // this stuck code so where to start this ? 

shared_ptr<threadWork> w(new someWork); 

pool.enqueue(w); 



return 0; 
} 
+1

我認爲提升已有線程池http://threadpool.sourceforge.net/ – Chipmunk

+0

感謝,我使用線程池從threadpool.sourceforge.net – vivek

+0

這個例子代碼不能編譯considuring,存在幾個誤區,一個例子'io_service_ .post(boost :: bin(&thread_pool :: wrap_task,this,workQueue));'應該是'boost :: bind' –

回答

0

你可以使用boost::asio::deadline_timer定期有你io_service更新代表隊列長度的原子變量。類成員函數可以按需返回隊列長度(按值)。