Subject: Re: send(), sendmsg(), sendto() not thread-safe

From: "Christopher Friesen" <[email-masked]>
Date: Wed, 17 May 2006 12:00:52 -0600

Benjamin Reed wrote:

> I think Mark's point isn't about "atomic" writes;
> instead, he was pointing out that when a programmer
> reads that a call is thread-safe he usually
> understands that to mean that it does not need to be
> protected by a lock when used by multiple threads.

<snip>

> This thread-safe issue is an even bigger deal when you
> are sharing the socket amoung many independent
> processes since locking in that context is a bit
> harder and more inefficient than in a pthread context.

There have always been possible issues with concurrent access to 
sockets/fds.

Consider what happens if you share a socket between processes/threads, 
you call select() in both of them, then do a blocking recv() in both to 
receive the message.  One of them gets the message, and the other blocks 
unexpectedly.

Or consider calling lseek() from one task, while doing successive read() 
calls in the other.

Or imagine one thread doing recvmsg() with MSG_PEEK, then calling 
recvmsg() to get the data, but meanwhile another thread has already read 
the message.

The calls themselves are thread-safe, but the side-effects of them may 
lead to unexpected behaviour unless the designer enforces appropriate 
synchronization.

Chris