2012-04-21 66 views
1

我想利用boost :: thread來執行「n」個類似的工作。當然,「n」通常可能會很高,所以我想限制同時運行的線程的數量爲一些小數目m(比如8)。我寫了類似下面的內容,在這裏我打開了11個文本文件,每次使用四個線程四個文件。boost :: thread在每次運行時產生不同的結果

我有一個小的類parallel(這在調用run()方法將打開一個輸出文件,並寫了一行它,採取在int變量。編譯順利,程序沒有任何警告運行,結果卻是。不按預期的方式創建的文件,但他們並不總是11號有誰知道什麼是我作出的錯誤

這裏的parallel.hpp:?

#include <fstream> 
#include <iostream> 

#include <boost/thread.hpp> 

class parallel{ 
public: 
    int m_start; 

    parallel() 
    { } 

    // member function 
    void run(int start=2); 
}; 

的parallel.cpp實現文件是

#include "parallel.hpp" 

void parallel::run(int start){ 

    m_start = start; 

    std::cout << "I am " << m_start << "! Thread # " 
      << boost::this_thread::get_id() 
      << " work started!" << std::endl; 

    std::string fname("test-"); 
    std::ostringstream buffer; 
    buffer << m_start << ".txt"; 

    fname.append(buffer.str()); 

    std::fstream output; 
    output.open(fname.c_str(), std::ios::out); 

    output << "Hi, I am " << m_start << std::endl; 

    output.close(); 

    std::cout << "Thread # " 
      << boost::this_thread::get_id() 
      << " work finished!" << std::endl; 
} 

而main.cpp中:

#include <iostream> 
#include <fstream> 
#include <string> 

#include <boost/thread.hpp> 
#include <boost/shared_ptr.hpp> 

#include "parallel.hpp" 

int main(int argc, char* argv[]){ 

    std::cout << "main: startup!" << std::endl; 
    std::cout << boost::thread::hardware_concurrency() << std::endl; 

    parallel p; 

    int populationSize(11), concurrency(3); 

    // define concurrent thread group 
    std::vector<boost::shared_ptr<boost::thread> > threads; 

    // population one-by-one 
    while(populationSize >= 0) { 
     // concurrent threads 
     for(int i = 0; i < concurrency; i++){ 
      // create a thread 
      boost::shared_ptr<boost::thread> 
      thread(new boost::thread(&parallel::run, &p, populationSize--)); 
      threads.push_back(thread); 
     }  
     // run the threads 
     for(int i =0; i < concurrency; i++) 
      threads[i]->join(); 

     threads.clear(); 
    } 

    return 0; 
} 

回答

0

您有與單個m_start成員變量,其所有線程沒有任何同步訪問單個parallel對象。

更新

這種競爭狀態似乎是一個設計問題的結果。目前還不清楚parallel類型的目標是什麼意思。

  • 如果它是爲了表示一個線程,那麼應該爲每個創建的線程分配一個對象。發佈的程序有一個對象和許多線程。
  • 如果它是爲了表示一組線程,那麼它不應該保留屬於單個線程的數據。
+0

是真的嗎?對於創建的文件肯定有不同的索引。 – 2012-04-21 19:40:17

+0

我不確定文件索引是什麼。文件具有不同的名稱,因爲文件系統不允許具有相同名稱的多個文件。 – 2012-04-21 19:51:28

+0

no-no ...我的代碼需要在「test-」的baseName後加m_start ... – 2012-04-21 20:17:05

相關問題