Download The JoCaml language Release 3.11 - The JoCaml system

Transcript
16
# let inc,get = create_counter ()
# ;;
val inc : unit -> unit = <fun>
val get : unit -> int = <fun>
This programming style is reminiscent of “object-oriented” programming: a counter is a thing
called an object, it has some internal state (count and its argument), and it exports some methods
to the external world (here, inc and get). The constructor create_counter creates a new object,
initializes its internal state, and returns the exported methods. As a consequence, several counters
may be allocated and used independently.
1.4
Control structures
Join pattern synchronization can express many common programming paradigms, either concurrent
or sequential.
1.4.1
Some classical synchronization primitives
Locks
Join pattern synchronization can be used to emulate simple locks:
# let new_lock () =
#
def free() & lock() = reply to lock
#
and unlock() = free() & reply to unlock in
#
spawn free() ;
#
lock,unlock
# ;;
val new_lock : unit -> (unit -> unit) * (unit -> unit) = <fun>
Threads try to acquire the lock by performing a synchronous call on channel lock. Due to the
definition of lock(), this consumes the name free and only one thread can get a response at
a time. Another thread that attempts to acquire the lock is blocked until the thread that has
the lock releases it by the synchronous call unlock that fires another invocation of free. As in
Objective Caml, it is possible to introduce several bindings with the and keyword. These bindings
are recursive.
To give an example of lock usage, we introduce a function that output its string argument
several times:
# let print_n n s =
#
for i = 1 to n do
#
print_string s; Thread.delay 0.01
#
done
# ;;
val print_n : int -> string -> unit = <fun>
The Thread.delay calls prevents the same thread from running long enough to print all its strings.
Now consider two threads, one printing *’s, the other printing +’s.