2012-02-03 63 views
1

所以我開始編寫一個程序來解析並處理大量的文本。我建立了一個包含以boost線程運行的方法的類。截至目前,每個這些線程都只是打印一些文本語句,然後返回。代碼編譯和運行沒有任何錯誤。但是,文本不一致地打印出來。這是因爲線程並行運行,因此我嘗試使用互斥鎖來協調輸出的使用。但是,我顯然做錯了,因爲輸出仍然不一致。爲了補充這些,一些輸出被打印了兩次,這是我無法解釋的,因爲它沒有正確編寫互斥鎖。下面是我的代碼:用增強線程庫打印

/* 
* File: ThreadParser.h 
* Author: Aaron Springut 
* 
* Created on Feburary 2, 2012, 5:13 PM 
*/ 

#ifndef THREADPARSER_H 
#define THREADPARSER_H 

#include <string.h> 
#include <iostream> 
#include <boost/thread/thread.hpp> 
#include <boost/thread/mutex.hpp> 
#include <boost/bind.hpp> 
#include "FileWordCounter.h" 

class ThreadParser { 

    public: 

    ThreadParser(); 
    ThreadParser(std::string fileName); 



    private: 

    //mutex for cout 
    boost::mutex coutMut; 

    std::string dataFile; 
    FileWordCounter fCounter; 

    //threads 
    void parseFile(); 
    void processSearches(); 



}; 

#endif  


/* 
* File: ThreadParser.cpp 
* Author: Aaron Springut 
* 
* Created on Feburary 2, 2012, 5:13 PM 
*/ 


#include "ThreadParser.h" 

using namespace std; 


ThreadParser::ThreadParser(){ 

    double buyNum = 0; 
    buyNum = buyNum * 100; 
    cout << "Percentage of people buying: "<< buyNum <<"%"<<endl; 

} 

ThreadParser::ThreadParser(string fileName){ 

    dataFile = fileName; 
    double buyNum = 0; 

    //create the mutex and aquire a lock on it for this thread 

    boost::mutex::scoped_lock(coutMut); 

    boost::thread parseThread(boost::bind(&ThreadParser::parseFile, this)); 
    boost::thread processSearches(boost::bind(&ThreadParser::processSearches,this)); 

    buyNum = buyNum * 100; 
    cout << "Percentage of people buying: "<< buyNum <<"%"<<endl; 


} 


void ThreadParser::parseFile(){ 

    boost::mutex::scoped_lock(coutMut); 
    cout << "parseFileThreadLaunch"<<endl; 
    return; 

} 


void ThreadParser::processSearches(){ 

    boost::mutex::scoped_lock(coutMut); 
    cout << "processSearchesLaunch"<<endl; 
    return; 

} 

至於什麼錯誤,這裏是來自運行此程序兩個輸出的一個例子:

Percentage of people buying: parseFileThreadLaunch 
processSearchesLaunch 
0% 

好吧,COUT不是線程安全的,我已經做了互斥體出現問題。

Percentage of people buying: parseFileThreadLaunch 
0% 
processSearchesLaunch 
processSearchesLaunch 

這很混亂,最後一行怎麼打印兩次?這是cout不是線程安全的結果嗎?或者,我是否缺少更大圖片的一部分。

編輯: 類是被稱爲像這樣的主要功能:

string fileName("AOLData.txt"); 
cout << fileName<< endl; 

ThreadParser tp(fileName); 
+0

你在做什麼來產生這個輸出?沒有'main'函數,所以我們不知道你在調用什麼方法,在什麼對象或什麼參數。 – 2012-02-03 05:04:56

+0

編輯:在這裏適合不好。所以我編輯了主帖。 – 2012-02-03 05:08:30

+0

一次調用該類的一個實例? – 2012-02-03 05:08:59

回答

2
boost::mutex::scoped_lock(coutMut); 

這不會做你認爲它。這會創建一個臨時的,立即銷燬,釋放鎖定。就像int(3);

你想:

boost::mutex::scoped_lock sl(moutMut); 

這將創建一個對象,sl,直到它超出範圍是持有鎖。

+0

這是問題,或者至少是其中的一部分。現在似乎可以在不中斷的情況下完成第一個打印語句。但是,它仍然有時會打印兩次,並且會將其他打印錯誤。 – 2012-02-03 05:16:33

+0

使用這個'main'函數和'scoped_lock'修復程序,它對我來說非常合適。 'int main(void) { string fileName(「AOLData.txt」); cout << fileName << endl; ThreadParser tp(fileName); sleep(1); }' – 2012-02-03 05:29:42

+0

添加睡眠(1)爲我做。我想主線程已經結束了,導致其他東西超出了範圍。 – 2012-02-03 05:32:48