caml-list - the Caml user's mailing list
 help / color / mirror / Atom feed
* Threads Scheduling
@ 2010-04-13 20:33 Gregory Malecha
  2010-04-13 20:54 ` [Caml-list] " Jake Donham
  2010-04-13 21:04 ` Daniel Bünzli
  0 siblings, 2 replies; 6+ messages in thread
From: Gregory Malecha @ 2010-04-13 20:33 UTC (permalink / raw)
  To: caml-list

[-- Attachment #1: Type: text/plain, Size: 1295 bytes --]

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

[-- Attachment #2: Type: text/html, Size: 1780 bytes --]

^ permalink raw reply	[flat|nested] 6+ messages in thread

end of thread, other threads:[~2010-04-14 18:18 UTC | newest]

Thread overview: 6+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2010-04-13 20:33 Threads Scheduling Gregory Malecha
2010-04-13 20:54 ` [Caml-list] " Jake Donham
2010-04-13 21:04 ` Daniel Bünzli
2010-04-13 21:56   ` Gregory Malecha
2010-04-14  8:40     ` Philippe Wang
2010-04-14 18:18       ` Goswin von Brederlow

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).