Concepts of Programming Languages

(Sean Pound) #1

620 Chapter 13 Concurrency


13.9.3 F#


Part of the F# support for concurrency is based on the same .NET classes
that are used by C#, specifically System.Threading.Thread. For example,
suppose we want to run the function myConMethod in its own thread. The
following function, when called, will create the thread and start the execution
of the function in the new thread:

let createThread() =
let newThread = new Thread(myConMethod)
newThread.Start()

Recall that in C#, it is necessary to create an instance of a predefined delegate,
ThreadStart, send its constructor the name of the subprogram, and send the
new delegate instance as a parameter to the Thread constructor. In F#, if a
function expects a delegate as its parameter, a lambda expression or a function
can be sent and the compiler will behave as if you sent the delegate. So, in the
above code, the function myConMethod is sent as the parameter to the Thread
constructor, but what is actually sent is a new instance of ThreadStart (to
which was sent myConMethod).
The Thread class defines the Sleep method, which puts the thread from
which it is called to sleep for the number of milliseconds that is sent to it as a
parameter.
Shared immutable data does not require synchronization among the
threads that access it. However, if the shared data is mutable, which is pos-
sible in F#, locking will be required to prevent corruption of the shared data
by multiple threads attempting to change it. A mutable variable can be locked
while a function operates on it to provide synchronized access to the object
with the lock function. This function takes two parameters, the first of which
is the variable to be changed. The second parameter is a lambda expression
that changes the variable.
A mutable heap-allocated variable is of type ref. For example, the follow-
ing declaration creates such a variable named sum with the initial value of 0 :

let sum = ref 0

A ref type variable can be changed in a lambda expression that uses the
ALGOL/Pascal/Ada assignment operator, :=. The ref variable must be pre-
fixed with an exclamation point (!) to get its value. In the following, the muta-
ble variable sum is locked while the lambda expression adds the value of x to it:

lock(sum) (fun () -> sum := !sum + x)

Threads can be called asynchronously, just as with C#, using the same
subprograms, BeginInvoke and EndInvoke, as well as the IAsyncResult
interface to facilitate the determination of the completion of the execution of
the asynchronously called thread.
Free download pdf