所以我開始編寫一個程序來解析並處理大量的文本。我建立了一個包含以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);
你在做什麼來產生這個輸出?沒有'main'函數,所以我們不知道你在調用什麼方法,在什麼對象或什麼參數。 – 2012-02-03 05:04:56
編輯:在這裏適合不好。所以我編輯了主帖。 – 2012-02-03 05:08:30
一次調用該類的一個實例? – 2012-02-03 05:08:59