[MLton] Re: exene example

Matthew Fluet fluet@cs.cornell.edu
Thu, 1 Sep 2005 10:50:14 -0400 (EDT)


>> Remember: the SML/NJ implementation of CML reimplements much of the IO 
>> sub-system of the Basis Library to both be thread safe and to play nice 
>> with switching threads.  In particular, the CML version of Socket.recvVec 
>> is implemented as follows:
>> 
>>     fun inEvt (CMLSock{sock, ...}) =
>>       CML.wrap(IOManager.ioEvt (OS.IO.pollIn (pollD sock)), ignore)
>> 
>>     fun recvVec (s as PS.CMLSock{sock, ...}, n) =
>>     case Socket.recvVecNB (sock, n)
>>      of (SOME res) => res
>>       | NONE => (CML.sync(inEvt s); Socket.recvVec (sock, n))
>> 
>> So, you can see that behind the scenes, it attempts a non-blocking receive; 
>> if that succeeds, it simply returns that data.  If the call would block, 
>> then it registers the socket with the IOManager, which takes care of 
>> polling io descriptors and resuming a thread once the io descriptor's state 
>> has changed (e.g., data has appeared on the socket).  It is the CML.sync on 
>> the (inEvt s) that makes the recvVec yield to other threads until such time 
>> as the socket has data.  Note, even though recvVec may be considered a 
>> blocking form of read (since the call won't return until there is actual 
>> data on the socket), other threads get a chance to run because it never 
>> performs a blocking system call unless it is certain that the call will not 
>> actually block.
>> 
>> The situation is entirely different in MLton (at the current time). There 
>> is no $(SML_LIB)/cml/basis.mlb corresponding to a thread safe / 
>> non-blocking implementation of the Basis Library.
>
> My port of state-threads to standard ML does this, if you are interested.
> However, it is quite different from CML...

It never hurts to see more examples.  That's why we have
http://www.mlton.org/Libraries and an open wiki.