Boost logo

Boost Users :

From: Gang Ma (contactmagang_at_[hidden])
Date: 2008-07-28 16:31:05


Hi,
I tried to use boost/thread library to write a program to read a large text
file. The program compiled but did not get the right answer. I am not sure
my usage of the library is correct. I appreciate your helps.

Here are the code:

#include <iostream>
#include <fstream>
#include <string>
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/bind.hpp>
#include <SQLAPI.h>
//#include "stdafx.h"

boost::mutex io_mutex;
using namespace std;

void mtread(char* filename,const int stidx, const int edidx,int id) {

    fstream infile;
    infile.open(filename);
    string line;
    if (infile.good()){

    for (int linenum=stidx; linenum<=edidx;linenum++) {
        boost::mutex::scoped_lock lock(io_mutex);

        infile.seekg(linenum,ios::beg);
        getline(infile,line);
        cout<<id << " : " <<line<<endl;
    }

}
 else
 { cerr<< "file " << filename << " cannot be opened for reading" <<endl;
 }

infile.close();
}

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

 boost::thread thrd1(boost::bind(&mtread, argv[1],0,4,1));
 boost::thread thrd2(boost::bind(&mtread, argv[1],5,9,2));

 thrd1.join();
 thrd2.join();

return 0;
}

I would like thread1 read linie 0-4 and thread2 read line 5-9. My dummy
test file has 10 lines, each line is 1,2, 3...,10 etc. My output is
2 :
2 : 3
2 :
2 :
1 : 1
1 :
1 :
1 : 2
1 :
2 : 4

regards,

Gang Ma



Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net