0

According to the POSIX standard, writes to a pipe are guaranteed to be atomic (if the data size is less than PIPE_BUF).

As far as I understand, this means that any thread trying to write to the pipe will never access the pipe in the middle of another thread's write. What's not clear to me is how this is achieved and whether this atomicity guarantee has other implications.

Does this simply mean that the writing thread acquires a lock somewhere inside the write function?

Is the thread that's writing to the pipe guaranteed to never be scheduled out of context during the write operation?

mklement0
  • 382,024
  • 64
  • 607
  • 775
athos
  • 1,281
  • 3
  • 14
  • 24
  • 1
    None of your inferences are guaranteed by the standard, so take that for what it is. All you know is that your write won't be interleaved with other writes, wether or not it acquires a lock to do this is an implementation detail, and I don't think the standard makes any kind of scheduling guarantees. The only thing it seems to imply is that no other thread will be able to write to the pipe as long as yours has a write pending, what happened between the scheduler and your thread between the time write() is called and it returns is none of your business :) – iluvcapra Dec 15 '16 at 03:56

1 Answers1

0

Pipe write are atomic upto the size of Pipe. Let assume that a pipe size is 4kb, then the write are atomic up to the data_size < 4kb. In the POSIX systems, kernel uses internal mutexes, and locks the file descriptors for the pipe. Then it allows the requesting thread to write. If any other thread requests write at this point, then it would have to wait for the first thread. After that the file descriptors are unlocked, so the other waiting threads can write to the pipe. So yes, kernel would not allow more than one thread to write to the pipe at the same time.

However, there is an edge case to think. If data of size close to 4kb has already been written, and the reading has not been done yet, then the pipe may not be thread safe. Because, at this point, it may be possible that the total bytes written to the pipe may exceed to the 4kb limit.

Mohmmed
  • 77
  • 9