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
Threads library
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2004-11-23 (20:10)
From: John Prevost <j.prevost@g...>
Subject: Re: [Caml-list] Threads library
On Tue, 23 Nov 2004 11:32:50 -0500 (EST), Ernesto Posse
<eposse@cs.mcgill.ca> wrote:
> If I understand
> correctly, the join affects only the thread created by ppp, but not
> those spawned from it. Is there a simple way to join the rest of the
> threads created?

The behavior of Thread.join is specifically to wait for that specific
thread to finish running.  Since your thread ppp simply creates two
other threads and then stops, joining with it waits until those two
threads have been created.  If you want to wait for all of the created
threads to complete, you'll need to do one of a handful of things:

1) The easiest solution is to have your function pp wait until all of
the threads it creates are complete before it exits.  For example:

let pp (x, y) =
  let a = create f x in
  let b = create f y in
    join a;
    join b

This isn't very extensible, but it's simple, and it works.  The main
lack of flexibility is that the function pp always waits for its
threads to complete, and sometimes you might just want to wait for all
of its subthreads to be created instead.

2) Another solution, which is mostly the same, is to have pp return
the threads it created, and let ppp decide what to do with them.  It's
probably better to change pp to return a list so that this is
extensible to more than two threads:

let pp (x, y) = [create f x; create f y]

let ppp (x, y) =
  create (fun () ->
    let subthreads = pp (x, y) in
    List.iter join subthreads)

This has the advantage that the calling function (ppp) gets to decide
whether to join with the subthreads or with the thread that creates
the subthreads.  It's still on the messy side--particularly because
everybody needs to know what threads go together.

3) You can create a pretty simple module that provides a way to group
threads together, by using the above List.iter technique.  This would
be more complicated, because a general solution needs to deal with
synchronization if multiple threads are creating threads in the
threadgroup, etc.  (I'm actually somewhat surprised that there's not
such a module already in the standard library.)  This would have the
advantage that everything could work the same way, and you can always
choose whether to join to an individual thread or to an entire
threadgroup.  I could whip something like this up later today,
although my first implementation was *too* naive, so I'm not including
it here.  :)