2010-08-11 76 views
1

的boost ::線程類有一個默認的構造函數,其給出了一個「不是一個線程」,那麼什麼是boost :: thread並創建它們的池!

boost::thread t1;

好?我可以給它一個函數來稍後在代碼中執行嗎?

而另一個問題:

我試圖寫它具有階段性架構(SEDA)一點點服務器,還有許多工作線程的每個階段和階段與事件隊列相連。當我使用boost :: thread_group創建4個工作線程池時,像這樣: (我已經刪除了隊列中的條件變量以清除此處,並且假設隊列的大小始終爲4N。)

boost::thread_group threads; 
while(!event_queue.empty()) 
{ 
    for(int i = 0; i < 4; ++i) 
    { 
     threads.create_thread(event_queue.front()); 
     event_queue.pop(); 
    } 

    threads.join_all(); 
} 

thread_group不斷增大。那些已完成的組中的線程會發生什麼情況,以及如何重用這些線程並將thread_group大小保持爲4?

我看到this question和,而不是上面的代碼中使用這樣的:

std::vector<boost::shared_ptr<boost::thread>> threads; 
while(!event_queue.empty()) 
{ 
    for(int i = 0; i < 4; ++i) 
    { 
     boost::shared_ptr<boost::thread> 
      thread(new boost::thread(event_queue.front()); 
     event_queue.pop(); 
     threads.push_back(thread); 
    } 

    for(int i = 0; i < 4; ++i) 
     threads[i]->join(); 

    threads.clear(); 
} 

有啥區別,哪一個具有更好的性能?會不會有內存泄漏?還是有另一種方法來創建一個簡單的線程池?

我很感激任何幫助。非常感謝你。

回答

相關問題