Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pread; threadsafe or not?

Is there a problem with using pread on the same file descriptor from 2 or more different threads at the same time?

like image 294
dan_waterworth Avatar asked Mar 01 '11 14:03

dan_waterworth


People also ask

What does not Threadsafe mean?

Not thread safe: Data structures should not be accessed simultaneously by different threads.

How do I know if a code is thread-safe?

To test if the combination of two methods, a and b, is thread-safe, call them from two different threads. Put the complete test in a while loop iterating over all thread interleavings with the help from the class AllInterleavings from vmlens. Test if the result is either an after b or b after a.

What does being Threadsafe mean?

In the simplest of terms threadsafe means that it is safe to be accessed from multiple threads. When you are using multiple threads in a program and they are each attempting to access a common data structure or location in memory several bad things can happen.

Are objects thread-safe?

A MessageService object is effectively immutable since its state can't change after its construction. So, it's thread-safe. Moreover, if MessageService were actually mutable, but multiple threads only have read-only access to it, it's thread-safe as well.


1 Answers

pread itself is thread-safe, since it is not on the list of unsafe functions. So it is safe to call it.

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

Regarding this, the specification says:

  • The behavior of multiple concurrent reads on the same pipe, FIFO, or terminal device is unspecified.

    Note that it doesn't mention ordinary files. This bit relates only to read anyway, because pread cannot be used on unseekable files.

  • I/O is intended to be atomic to ordinary files and pipes and FIFOs.

    But this is from the non-normative section, so your OS might do it differently. E.g., if you read from two threads and there is a concurrent write, you might get different pieces of the write in your two read buffers. But this kind of problem is not specific to multithreading.

Also nice to know that in some cases

read() shall block the calling thread

Not the process, just the thread. And

A thread that has blocked shall not prevent any unblocked thread [...] from eventually making forward progress

like image 195
aaz Avatar answered Oct 01 '22 14:10

aaz