使用增强线程库打印
Printing with boost threading library
因此,我开始编写一个程序来解析并处理大量文本。我已经建立了一个类,其中包含作为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++中打印线程 ID 吗?
- 我需要线程函数在不停止实际程序的情况下,每2秒打印一次随机数
- 如何在没有同步的情况下使用多个线程(2、4,8、16 个线程)在循环(10,100、1000 个周期)中打印字符串?
- 线程函数不打印
- 在 C Linux 中使用三个线程使用信号量同步按顺序打印 3 4 5 50 次
- 多线程日志打印先验C
- 为什么奇怪的从带有互斥锁的线程打印
- 如何在多线程 MEX 函数中打印到控制台?
- 在所有线程未完成打印时提升线程
- 当一个线程希望执行或打印某个内容时,如何挂起其他线程
- 多线程程序只适用于打印语句
- 具有多个线程的程序,不打印预期输出
- C++线程意外地打印多次相同的行
- 如何使用 boost.log 以 dec 格式打印进程 ID 和线程 ID
- 中断时提升线程不打印退出消息
- 以线程安全的方式每秒打印队列的当前元素数
- lldb/Xcode:如何打印线程索引、id或名称
- 使用增强线程库打印
- 像"__LINE__"一样,C/C++ 中是否有任何打印线程名称或 ID 的标准宏?
- 打印线程的调用栈(c++),是否为StackWalker