Description
openedon Mar 1, 2021
The approach outlined in this comment
probably is inefficient on linux. The kernel recently gained an optimization where a write to a pipe only wakes up one reader as long as that one reader empties the pipe: torvalds/linux@0ddad21 Note the wake_next_reader
flag.
Waking up a polling process will never empty the pipe since it first has to return to userspace before that might issue a read syscall, So it'll end up waking more readers than necessary which leads to lots of unnecessary context switches and wasted CPU cycles.
It would be better to simply attempt reading from the fd and only start polling when it returns EWOULDBLOCK
.
It might even be beneficial to dup()
the file descriptor and explicitly set the copy to blocking mode if the current process has no need for non-blocking operation.
Edit: I included a lot of hedge words, but here's the word of god saying that poll-based wakeups indeed do not benefit from that optimization: https://lkml.org/lkml/2020/2/12/1019