Boost logo

Boost Users :

From: Anthony Williams (anthony.ajw_at_[hidden])
Date: 2008-07-28 16:50:00


"Gang Ma" <contactmagang_at_[hidden]> writes:

> 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 : 32 :
> 2 :1 : 11 :1 :1 : 21 :2 : 4regards,Gang Ma

This looks to me like an IO problem, not a thread problem.

Replace your threads with direct calls to the functions, and I expect
you'll see the same problem. seekg does not seek to a line, it seeks
to a byte in the file.

Anthony

-- 
Anthony Williams            | Just Software Solutions Ltd
Custom Software Development | http://www.justsoftwaresolutions.co.uk
Registered in England, Company Number 5478976.
Registered Office: 15 Carrallack Mews, St Just, Cornwall, TR19 7UL

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