Team BBL
Previous Page Next Page

12.10. Threads and I/O

We introduced the pread and pwrite functions in Section 3.11. These functions are helpful in a multithreaded environment, because all threads in a process share the same file descriptors.

Consider two threads reading from or writing to the same file descriptor at the same time.

Thread A

Thread B

lseek(fd, 300, SEEK_SET);

lseek(fd, 700, SEEK_SET);

read(fd, buf1, 100);

read(fd, buf2, 100);


If thread A executes the lseek and then thread B calls lseek before thread A calls read, then both threads will end up reading the same record. Clearly, this isn't what was intended.

To solve this problem, we can use pread to make the setting of the offset and the reading of the data one atomic operation.

Thread A

Thread B

pread(fd, buf1, 100, 300);

pread(fd, buf2, 100, 700);


Using pread, we can ensure that thread A reads the record at offset 300, whereas thread B reads the record at offset 700. We can use pwrite to solve the problem of concurrent threads writing to the same file.

    Team BBL
    Previous Page Next Page