所以我开始编写一个程序来解析并处理大量的文本。我建立了一个包含以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