C read and thread safety (linux)

Jeremy Cochoy picture Jeremy Cochoy · Jul 2, 2013 · Viewed 11.5k times · Source

What would happen if you call read (or write, or both) in two different thread, on the same file descriptor (lets says we are interested about a local file, and a it's a socket file descriptor), without using explicitly a synchronization mechanism?

Read and Write are syscall, so, on a single core CPU, it's probably unlucky that two read would be executed "at the same time". But with multiple cores...

What the linux kernel will do?

And let's be a bit more general : is the behavior always the same for other kernels (like BSDs) ?

Edit : According to the close documentation, we should be sure that the file descriptor isn't used by a syscall in an other thread. So it seams that explicit synchronization would be required before closing a file descriptor (and so, also around read/write if thread that may call it are still running).

Answer

Sergey L. picture Sergey L. · Jul 2, 2013

Any system level (syscall) file descriptor access is thread safe in all mainstream UNIX-like OSes. Though depending on the age they are not necessarily signal safe.

If you call read, write, accept or similar on a file descriptor from two different tasks then the kernel's internal locking mechanism will resolve contention.

For reads each byte may be only read once though and writes will go in any undefined order.

The stdio library functions fread, fwrite and co. also have by default internal locking on the control structures, though by using flags it is possible to disable that.