SriPriya G wrote:
> When a thread, say t1 spawns a whole lot of child threads and  
> subsequently if t1 gets terminated explicitly (by Thread.terminate),  
> do the child threads also get terminated.
>
> I did some preliminary experiments to understand this behaviour.
> Does someone know of the details of how exactly this sort of a  
> scenario is handled.
>
> I am also interested in the extension of the scenario to a whole  
> function call within which a lot of threads get spawned and after the  
> function returns, what happens to the threads that were spawned?
>   
The life time of a thread is not limited by the life time of its 
creator. There is no notion of hierarchy or ownership for threads. If 
you want "child" threads to die with their "parent" then you have to 
program that up manually, e.g. by installing an exception handler in the 
parent and kill its children there. It is relatively straightforward to 
do this as an abstraction (untested):

signature HTHREAD = (* hierarchical threads *)
sig
    type hthread
    val spawnThread : hthread * (unit -> 'a) -> hthread * 'a
    val terminate : hthread -> unit
end

structure HThread :> HTHREAD =
struct
    type hthread = Thread.thread * Thread.thread list ref
    fun terminate (t, _) = Thread.terminate t
    fun wrap (f, children) () =
        f () handle e =>
            List.app (fn ht => terminate ht
                         handle Thread.Terminated => ()) (!children)
    fun spawnThread ((self, children), f) =
        let
            val grandchildren = ref []
            val (child, x) = Thread.spawnThread (wrap (f, grandchildren))
        in
            children := child :: !children;
            (child, grandchildren)
        end
end

Note however that such a behaviour (like external thread killing in 
general) is not a particularly good idea if your threads have non-local 
side effects. In particular, if you synchronise with locks somewhere, 
you need to protect the locking code.

- Andreas


_______________________________________________
alice-users mailing list
[email protected]
http://www.ps.uni-sb.de/mailman/listinfo/alice-users

Reply via email to