English version
Accueil     Ŕ propos     Téléchargement     Ressources     Contactez-nous    

Ce site est rarement mis ŕ jour. Pour les informations les plus récentes, rendez-vous sur le nouveau site OCaml ŕ l'adresse ocaml.org.

Browse thread
Sending a signal to a thread
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2008-11-09 (18:02)
From: Daniel_Bünzli <daniel.buenzli@e...>
Subject: Sleeping and waking up a thread (was Re: Sending a signal to a thread)

Le 9 nov. 08 ŕ 16:00, Daniel Bünzli a écrit :

> Is there a way to send a signal to a thread from another thread  
> (i.e. something like pthread_kill) ?

Sorry to respond to myself. This is not the answer to the question  
(which I believe is no) but it does solve my problem.

The actual problem was to be able to sleep a thread for a specific  
amount of time unless another thread woke it before. For the latter  
operation I just wanted to send a sigalrm to the thread from the other  
thread since this signal is already used to manage the sleep timer.

Anyway there's a workaround with condition variables. See the code  
below (n.b. handles only one sleeping thread, as the signal handler is  
shared between threads.)



let sleep, wakeup =
   let m = Mutex.create () in
   let proceed = Condition.create () in
   let sleeping = ref false in
   let set_timer d =
     let s = { Unix.it_interval = 0.; it_value = d } in
     ignore (Unix.setitimer Unix.ITIMER_REAL s)
   let sleep d =                              (* with d = 0. unbounded  
sleep. *)
     Mutex.lock m;
     sleeping := true;
     set_timer d;
     while !sleeping do Condition.wait proceed m done;
     Mutex.unlock m
   let wakeup () =
     Mutex.lock m;
     sleeping := false;
     set_timer 0.;
     Mutex.unlock m;
     Condition.signal proceed
   let timer _ = sleeping := false; Condition.signal proceed in
   Sys.set_signal Sys.sigalrm (Sys.Signal_handle timer);
   sleep, wakeup