2016-02-11 46 views
0

我試圖在任何時候限制線程的數量,使其等於最大可用內核的數量。以下是一個合理的方法嗎?有更好的選擇嗎?謝謝!Boost thread_group線程限制器

boost::thread_group threads; 
    iThreads = 0; 

    for (int i = 0; i < Utility::nIterations; i++) 
    { 

     threads.create_thread(
      boost::bind(&ScenarioInventory::BuildInventoryWorker, this,i)); 

     thread_limiter.lock(); 
     iThreads++; 
     thread_limiter.unlock(); 

     while (iThreads > nCores) 
      std::this_thread::sleep_for(std::chrono::milliseconds(1)); 

    } 

threads.join_all(); 


void ScenarioInventory::BuildInventoryWorker(int i) 
{ 
    //code code code.... 

    thread_limiter.lock(); 
    iThreads--; 
    thread_limiter.unlock(); 
} 

回答

0

你很可能在尋找的是帶有任務隊列的thread_pool。

有固定數量的線程阻塞隊列。每當一個任務被推入隊列時,一個工作線程就會發出信號(條件變量)並處理任務。

這樣,你

  • 沒有(低效率)等待鎖
  • 沒有任何更多的線程,比「最大」
  • 沒有在代碼中阻止他們推送任務
  • 沒有多餘的線程的創建圍繞

每次看到這個答案對於這樣一個THRE兩個不同的演示有任務隊列的廣告池:Calculating the sum of a large vector in parallel