Concepts of Programming Languages

(Sean Pound) #1
13.9 Concurrency in Functional Languages 619

13.9.2 Concurrent ML


Concurrent ML (CML) is an extension to ML that includes a form of threads
and a form of synchronous message passing to support concurrency. The lan-
guage is completely described in Reppy (1999).
A thread is created in CML with the spawn primitive, which takes the
function as its parameter. In many cases, the function is specified as an anony-
mous function. As soon as the thread is created, the function begins its execu-
tion in the new thread. The return value of the function is discarded. The
effects of the function are either output produced or through communications
with other threads. Either the parent thread (the one that spawned the new
thread) or the child thread (the new one) could terminate first and it would not
affect the execution of the other.
Channels provide the means of communicating between threads. A chan-
nel is created with the channel constructor. For example, the following state-
ment creates a channel of arbitrary type named mychannel:

let val mychannel = channel()

The two primary operations (functions) on channels are for sending
(send) and receiving (recv) messages. The type of the message is inferred
from the send operation. For example, the following function call sends the
integer value 7 , and therefore the type of the channel is then inferred to be
integer:

send(mychannel, 7)

The recv function names the channel as its parameter. Its return value is
the value it received.
Because CML communications are synchronous, a message is both sent
and received only if both the sender and the receiver are ready. If a thread
sends a message on a channel and no other thread is ready to receive on that
channel, the sender is blocked and waits for another thread to execute a recv
on the channel. Likewise, if a recv is executed on a channel by a thread but no
other thread has sent a message on that channel, the thread that ran the recv
is blocked and waits for a message on that channel.
Because channels are types, functions can take them as parameters.
As was the case with Ada’s synchronous message passing, an issue with
CML synchronous message passing is deciding which message to choose when
more than one channel has received one. And the same solution is used: the
guarded command do-od construct that chooses randomly among messages
to different channels.
The synchronization mechanism of CML is the event. An explanation
of this complicated mechanism is beyond the scope of this chapter (and this
book).
Free download pdf