[Haskell-cafe] Computations that can time out + gathering
feedback from threads
Sebastian Sylvan
sebastian.sylvan at gmail.com
Mon Oct 31 16:42:36 EST 2005
On 10/31/05, Joel Reymont <joelr1 at gmail.com> wrote:
> Folks,
>
> I need to implement computations that can time out (connecting to a
> server, reading from socket, etc.), plus gather feedback from a few
> thousands of threads. What is the best way to implement this?
>
> Do I launch a thread to sleep and a thread to connect/read from
> socket and use something like Shared Transaction Memory to wait for
> either of the two to finish?
Well you could do it something like this (warning all of this is
untested written off the top of my head, most of it is variations of
stuff seen elsewhere):
parIO f1 f2 = do m <- newEmptyMVar
tid1 <- forkIO (child f1 m)
tid2 <- forkIO (chid f2 m)
res <- takeMVar m
killThread tid1
killThread tid2
return res
child f m = catch (f >>= putMVar m) (const ())
parIO can then be used to run two actions simulatenously and return
when the first of them gets done, which can be used to run an action
in parallel with a sleeping action.
timetout f d = threadDelay d `parIO` f
> Also, my "simple scripting engine" launches a few thousands of
> scripts that connect to a server, exchange commands and update their
> internal state. I need to wait for all these to finish and get the
> results of their execution. My scripts are a combination of monads
> and I run them with runXXX( ... ) from the IO monad so that I can
> inspect the resulting state.
>
> Is there an elegant solution for waiting for all the threads to
> complete and then figuring out how many of these are in good share
> according to their end state?
Well. You could make all of these scripts write their results to an
MVar (which you pass to them when they start). That way you could just
have a list of these MVars and do something like:
results <- mapM takeMVar resultsMvars
When that computations finishes, all the MVars will have been filled
(and read), which can only happen after all the scripts have finished
(filling in their own MVar).
/S
--
Sebastian Sylvan
+46(0)736-818655
UIN: 44640862
More information about the Haskell-Cafe
mailing list