Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C read and thread safety (linux)

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).

like image 491
Jeremy Cochoy Avatar asked Jul 02 '13 17:07

Jeremy Cochoy


1 Answers

Have a care for those who follow in your footsteps

It's perfectly normal to protect the file descriptor with a mutex semaphore. It removes any dependence on kernel behaviour so your message boundaries are now certain. You then don't have to cite the last paragraph at the bottom of a 15,489 line manpage which explains why the mutex isn't necessary (I exaggerated, but you get my meaning)

It also makes it clear to anyone reading your code that the file descriptor is being used by more than one thread.

Fringe Benefit

There is a fringe benefit to using a mutex that way. Suppose you've got different messages coming from the different threads and some of those messages are more important than others. All you need to do is set the thread priorities to reflect their messages' importance. That way the OS will ensure that your messages will be sent in order of importance for minimal effort on your part.

like image 150
bazza Avatar answered Oct 06 '22 01:10

bazza