2012-02-03 38 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