使用增强线程库打印

Printing with boost threading library

本文关键字:打印 线程 增强      更新时间:2023-10-16

因此,我开始编写一个程序来解析并处理大量文本。我已经建立了一个类,其中包含作为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);
boost::mutex::scoped_lock(coutMut);

这并不像你想象的那样。这会创建一个临时的,它会立即被销毁,从而释放锁。就像int(3);一样。

您想要:

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

这将创建一个对象sl,该对象保持锁,直到锁超出作用域。