lec16 - (* Concurrency and multi-threaded OCaml programs *)...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
(* Concurrency and multi-threaded OCaml programs *) (* Programs that use system threads must be linked as follows: * ocamlc -thread other options unix.cma threads.cma other files * ocamlopt -thread other options unix.cmxa threads.cmxa other files * * To get a version of the ocaml top level with threads, run: * ocamlmktop -thread unix.cma threads.cma -o mytop * Then run the resulting executable: ./mytop -I +threads *) (* Sharing variables across threads yields unpredictable results * unless done in a thread-safe manner. Here the shared variable * "result" can decrease even though threads accessing it only try to * increase its value! *) let prog1 (n) = let result = ref 0 in let f (i) = for j = 1 to n do let v = !result in Thread.delay(Random.float 1.0); result := v+i; print_string("Value " ^ string_of_int(!result) ^ "\n"); flush stdout f done in ignore (Thread.create f 1); ignore (Thread.create f 2) (* Using mutual exclusion, commonly called a mutex, to guarantee * thread safety. One party at a time can have control over a mutex, * other parties that wish to use it must wait for the current party to * release it. Mutex.lock acquires the specified mutex, blocking until * it can be acquired (i.e., waiting until no other party has it * locked). Mutex.unlock frees the mutex for others to access. * * Too much locking with mutexes results in code not being concurrent; * in fact maybe slower than a single-threaded version. But sharing * variables without being thread-safe will yield unpredictable * behavior! Concurrency is hard. Often a good approach is to write * code in as functional a style as possible. *) let prog2 (n) = let result = ref 0 in let m = Mutex.create() in let f (i) = for j = 1 to n do Mutex.lock m; let v = !result in Thread.delay(Random.float 1.0); result := v+i;
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 4

lec16 - (* Concurrency and multi-threaded OCaml programs *)...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online