Pread thread safe or not?

Is there a problem using pread in the same file descriptor from two or more different threads at the same time?

+5
source share
4 answers

pread itself is thread safe because it is not in the list of unsafe functions . So it can be called safe.

The real question is: what happens if you read the same file at the same time (not necessarily from two threads, but also from two processes).

Regarding this, the specification says:

  • The behavior of multiple concurrent reads on the same channel, FIFO, or terminal device is not specified.

    Please note that it does not mention regular files. This bit only applies to read in any case, because pread cannot be used in files with unspeakable files.

  • I / O is for atomic regular files and channels and FIFOs.

    But this is from a non-normative section, so your OS may do it differently. For example, if you are reading from two streams and there is simultaneous writing, you can get different parts of the writing in your two reading buffers. But such a problem is not specific to multithreading.

It’s also nice to know that in some cases

read () blocks the calling thread

Not a process, just a stream. AND

A thread that is blocked should not prevent an unlocked thread [...] from moving forward.

+8
source

Since we use the same fd, we need to bind the lock, otherwise there will be a mixed data set of two pread in the file descriptor. So yes, there is a problem with this

http://linux.die.net/man/2/pread

-1
source

The pread () function should be equivalent to read (), except that it should read from a given position in the file without changing the file pointer. The first three pread () arguments are the same as read () with the fourth offset argument added for the desired position within the file. Attempting to execute pread () on a file that cannot be found will result in an error.

"The read() function itself is thread-oriented," as mentioned on this page. However, the lseek() function is not thread-oriented.

In glibc, the pread() function calls read() to get the data and lseek() to find the read position in the file, and then sets the position for the old position.

Conclusion: pread() not a threaded pread() .

-2
source

I'm not 100% sure, but I think that the file descriptor structure itself is not thread safe, so two simultaneous changes to it would ruin it. You need some kind of lock.

-3
source

Source: https://habr.com/ru/post/1341822/


All Articles