gpt4 book ai didi

c++ - 使用 boost 线程库打印

转载 作者:行者123 更新时间:2023-11-30 04:29:45 24 4
gpt4 key购买 nike

所以我开始写一个程序来解析然后处理大量的文本。我已经设置了一个类,其中包含作为 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,它持有锁直到它超出范围。

关于c++ - 使用 boost 线程库打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9123889/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com