Hello,

I'm trying to write a function (run_guarded) that takes another function (f), and runs it for some amount of time. If f terminates with value x, then the result of run_guarded should be Some x, otherwise it should be None. Here's my implementation using the Thread library:

let run_guarded f x = 
  let res = ref None in
  let m   = Mutex.create () in
  let c   = Condition.create () in
  let _ = Mutex.lock m in
  let tid1 = Thread.create (fun x -> 
    let z = f x in
    let _ = res := Some z in
    let _ = Mutex.lock m in
    let _ = Mutex.unlock m in
    let _ = Condition.broadcast c in
    ()) x
  and tid2 = Thread.create (fun () ->
    let _ = Thread.delay 0.3 in
    let _ = Mutex.lock m in
    let _ = Mutex.unlock m in
    let _ = Condition.broadcast c in
    ()) ()
  in
  let _ = Condition.wait c m in
  let _ = Mutex.unlock m in
  let _ = try Thread.kill tid2 with _ -> () in
  let _ = try Thread.kill tid1 with _ -> () in
  !res

It seems like it should work, but it doesn't work if the function f doesn't terminate. It seems to be running everything serially. I know that threads aren't actually parallel, but I thought they were preemptive in which case it seems like this should work. Does anyone know what I did wrong here?

Thank you very much.

--
gregory malecha