multithreading - Multiple threads reading from the same file sharing one handler -
c++11, multiplatform code, threads std::thread. have 1 open file , multiple threads have read it.
premise: @ first had 1 string held path file, each new thread opened file, read it, closed it. worked @ point realized maybe bit slow purpose. have file* opened in class constructor , closed in destroy, , multiple threads reading same file. reading, no writing.
i know has been long discussed in other questions, haven't found answer specific questions, are:
1) safe so? 2) faster have multiple threads accessing same handler rather having each thread doing open/close tasks? 3) can o.s. interfere in way threads?
some example code:
before (thread opens/closes file):
void continuepreload(int sn, unsigned long bytesize) { // open file file *fpfile = fopen(openfile, "rb"); // seek position fseek(fpfile, wavepointers[sn] + preloadbytesize[sn], seek_set); // read portion fread(&sampledata[sn][preloadbytesize[sn] / sizeof(short)], 1, bytesize - preloadbytesize[sn], fpfile); // close file fclose(fpfile); } now (thread accesses open file):
void continuepreload(int sn, unsigned long bytesize) { // no need open/close file again, seek position... fseek(openfp, wavepointers[sn] + preloadbytesize[sn], seek_set); // , read desired data fread(&sampledata[sn][preloadbytesize[sn] / sizeof(short)], 1, bytesize - preloadbytesize[sn], openfp); }
the code wrong. have race multiple threads accessing same file handler , moving "current pointer" concurrently without synchronisation. being correct need protect file descriptor mutex. locking / unlocking make slower opening file once per thread.
your first solution better (correct , fast).
Comments
Post a Comment