[Mono-list] Re: full duplex sockets and threads

Robert Jordan robertj at gmx.net
Mon May 8 08:44:31 EDT 2006


P. Oscar Boykin wrote:
> According to this:
> 
> http://groups.google.com/group/comp.protocols.tcp-ip/browse_thread/thread/7f695ec1d8f83253/b11f53da207558cc?lnk=st&q=sending+and+receiving+sockets+simultaneously+linux&rnum=14&hl=en#b11f53da207558cc 
> 
> 
> It is safe to use a socket in most unices in two threads if one does only
> reading and one does only writing.
> 
> Is this true of Mono/C#?
> 
> The only documentation I can find is from Socket:
> 
> "All public static members of this type are safe for multithreaded
> operations. No instance members are guaranteed to be thread safe."
> 
> Which I believe is boilerplate, but would imply that it might not be 
> safe to
> read in one thread and write in another.

The boilerplate just states that the implementation of
a certain class is not thread safe. It doesn't mean that
the underlying technology is not thread safe.

> My experiments suggest that reading in one thread and writing in another
> works in mono (tested with UDP), but I am wondering if there is an
> "official" position.  Is this unclear in the .Net class library?  Might it
> stop working in the future and not be considered a bug?

It's common sense that [Begin|End]Receive[From] and
[Begin|End]Send[To] are thread safe.

[In MS.NET 2.0, the Socket class is even marked as thread safe.]

> The case I am working with is the following: two hosts have a socket 
> between
> them.  At any time one or the other may send data.  What is the lowest
> latency way to make sure that data is sent quickly and received quickly.
> Being strict about the documentation would imply it is not safe to do a
> blocking read in one thread while sending in another thread.  Thus, it 
> seems
> that polling (or select) is required, both of which introduce latency.
> 
> If anyone else has some good pointers on how to use one socket to send and
> receive without polling or using the asynchronous methods I would be happy
> to learn of them (polling introduces latency and the asynchronous methods
> often lead to deadlocks I guess due to their internal use of threadpools).

Supposing the reads & writes are highly interdependent, using
asynchronous methods is the fastest way. Having separate threads
for reading and writing needs thread synchronization and leads
to a context switch.

The async methods used by the Socket class are handled differently
by the runtime. They are not invoked from the generic TP. The Socket
IO is handled by a specialized thread using AIO APIs.

BTW, the TP issues have been fixed in the meanwhile:

http://www.mono-project.com/Article:ThreadPool_Deadlocks
(see "Long Term Solutions")

Robert



More information about the Mono-list mailing list