File: cothread.ml

package info (click to toggle)
cothreads 0.10-7
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 500 kB
  • sloc: ml: 1,963; makefile: 216
file content (24 lines) | stat: -rw-r--r-- 767 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
include Thread

let spawn f x = 
  let ch = Event.new_channel () in
  let result = ref `Unknown in
  let thread_fun () =
    let res = try `Result (f x) with e -> `Exn e in
    Event.sync (Event.send ch res) in
  ignore (Thread.create thread_fun ());
  let rec launch () = match !result with 
    | `Result v -> Event.always v
    | `Exn e -> raise e
    | `Unknown -> 
        Event.wrap (Event.receive ch) 
          (fun res -> result:= res; Event.sync (launch ())) in
  Event.guard launch

let spawnl f x =
  let ch = Event.new_channel () in
  let thread_fun () = Event.sync (Event.send ch (f x)) in
  let launch () = 
    let _worker = Thread.create thread_fun () in
    Event.wrap_abort (Event.receive ch) (fun () -> invalid_arg "kill") in
  Event.guard launch