2007-01-21

Reading File in a Multi-Thread Environment

A file can be opened separately in a multi-thread environment, but it can not be read independently. It seems there is a unique reading pointer inside OS. When a thread reads some bytes, the pointer is advanced, and other threads will continue reading from the new position. To control the reading behaviour, file operations must be synchronized. Look at the following piece of code:

unsigned long pos = 0;
unsigned long bytesRead = 0;
for (;;) {
    mutex_->captureObject();
    fseek(f, pos, SEEK_SET);
    bytesRead = fread(buffer, 1, BUFFSIZE, f);
    mutex_->releaseObject();
    if (bytesRead <= 0)
        break;
    pos += bytesRead;
    .......
}

A mutex object is used to synchronize file operations.

0 Comments:

Post a Comment

<< Home