boost thread/conditional variable test example

Three threads read lines from a file, process lines in parallel and then write lines to a new file as the same order as the lines are read out. The new file should be as the same as input file. Input file is text file.

 

/build:
//g++ xxx.cpp -lboost_thread-mt

#include <boost/thread.hpp>
#include <iostream>
#include <boost/shared_ptr.hpp>
#include <fstream>

using namespace std;

ifstream fp;
int lineId = 0;
ofstream fp2;

boost::mutex lineReadMutex;
boost::mutex lineSaveMutex;
boost::condition_variable lineSaveVariable;
//Next saving line
int saveLineNum = 1;

int handleLine(const string& line) {
//Simulate some heavy work
int sum = 0;
for (int loop = 0; loop < 30000; ++loop) {
for (int i = 0; i < line.size(); ++i) {
sum += (long)line[i];
}
}
return 1;
}

 

void saveLine(const string& line, int lineNum) {
boost::mutex::scoped_lock lock(lineSaveMutex);

// It’s my turn
while (saveLineNum != lineNum) {
lineSaveVariable.wait(lock);
}

fp2 << line << endl;
cout << “save line ” << lineNum << “\n”;
++saveLineNum;
lock.unlock();

lineSaveVariable.notify_all();
}
bool getLine(string& line, int& lineNum) {
boost::mutex::scoped_lock lock(lineReadMutex);
if (getline(fp, line)) {
lineNum = ++lineId;
return true;
}
return false;
}

 

void task() {
string line;
int lineNum;
while(getLine(line, lineNum)) {
int tmp = handleLine(line);
saveLine(line, lineNum);
}
}

int main(int argc, char** argv) {

if (argc < 3) return -1;

// input file name
fp.open(argv[1]);
if (!fp.is_open()) return -1;

// output file name
fp2.open(argv[2]);
if (!fp2.good()) return -1;
boost::thread thr_1(task);
boost::thread thr_2(task);
boost::thread thr_3(task);
thr_1.join();
thr_2.join();
thr_3.join();

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值