Posted By

keigoi on 09/10/09


Tagged

OCaml


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

keigoi


OCaml memory allocation and context switching


 / Published in: Other
 

OCaml runtime is known to do context switch at the point allocation occurs (confirmed on current version 3.11.1). This snippet shows that context switch never occurs if the thread does not do any allocation, i/o nor synchronization. compile with:

ocamlopt -thread -I +threads -I unix unix.cmxa threads.cmxa filename.ml

the function allocation allocates some memory on OCaml side, while allocation2 does on C side. In latter case allocation never occur on OCaml side, hence context doesn't switch, and one of the thread runs forever, while the other starves.

See also:http://snipplr.com/view/19485/

  1. let allocation _ = let rec gen x = if x=0 then [] else x::gen (x-1) in ignore (gen 100000)
  2. let allocation2 _ = ignore (String.create 1000000) (* process runs forever if we use this allocation *)
  3.  
  4. let r = ref false;;
  5.  
  6. let rec forever x = allocation (); r:=true; forever x;;
  7.  
  8. let rec wait _ = if !r then print_string "end.\n" else (allocation (); wait ()) ;;
  9.  
  10. Thread.create (fun _ -> forever ()) ();;
  11.  
  12. wait ();;

Report this snippet  

You need to login to post a comment.