所以我开始编写一个解析然后处理大量文本的程序。我已经设置了一个包含作为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 :(得分:2)
boost::mutex::scoped_lock(coutMut);
这不符合你的想法。这会创建一个临时的,立即销毁,释放锁。就像int(3);
。
你想:
boost::mutex::scoped_lock sl(moutMut);
这将创建一个对象sl
,该对象持有锁,直到它超出范围。