views:

49

answers:

2

As Windows doesn't provide UNIX domain sockets, I am using a a local TCP connection to simulate the behaviour. Now, POSIX guarantees that if several threads are writing to the UNIX domain socket in parallel, chunks up to PIPE_BUF will be handled atomically - i.e. no interleaving will happen. Is there are similar guarantee on local TCP winsock or do I have to synchronise the writers using critical section?

A: 

Its not explicitly guaranteed. Lock. Uncontended locks are cheap unless you are in an extremely tight loop. If you really don't want to do this, use overlapped i/o.

RdM
How does using overlapped I/O help here? If he has multiple threads writing to the same socket then distinct independent writes will interleave unless he locks...
Len Holgate
Hm, actaully, using local UDP may help to get the behaviour...
sustrik
But I assume there's no guarantee that UDP packets gets throught the local network stack.
sustrik
A: 

If you have several threads writing to the same socket then each write call will be atomic but each interleaved with respect to other write calls that are occurring on different threads;

So, if you have thread 1 writing a string of A's in a single write and thread 2 writing a series of B's with one write and a series of C's with another then you might get ABC, or BAC or BCA but you wont get a broken run of A's with some B's in the middle...

If you require that the two writes that are being issued by thread 2 are not interleaved with the write that is issued by thread 1 (that is ABC and BCA are fine but BAC is not) then you should either use a single call to WSASend() in thread 2 with the two buffers in an array of WSABUF structs (scatter/gather writing) or you need to lock around the write calls so that thread 1 can't interrupt.

Len Holgate
Great. I've meant the former. Is the behaviour documented somewhere?
sustrik
Not as such, though I've been writing overlapped I/O servers using this assumption for over 10 years now and that's always the behaviour that I've seen; you could take this "WSASend should not be called on the same socket simultaneously from different threads, because it can result in an unpredictable buffer order." from here: http://msdn.microsoft.com/en-us/library/ms742203(VS.85).aspx as an indication that buffers themselves are not split; but it's vague...
Len Holgate