[Haskell-cafe] Suggestiong for inter-thread communication

Ertugrul Söylemez es at ertes.de
Sat Jan 26 11:46:21 CET 2013


Erik de Castro Lopo <mle+hs at mega-nerd.com> wrote:

> > Do you need advice on what? I didn't understand your last phrase.
>
> Well I have data from two sources, stdin and the calculation
> thread. If I was doing this in C, I'd probably use a pipe for the
> calculation data and then do select on the two file descriptors.
>
> There is a select package:
>
>     http://hackage.haskell.org/package/select
>
> but I was wondering if there was a more idiomatic Haskell way of
> dealing with inputs from more than one source.

Of course.  Threads communicate through MVars, Chans and other
abstractions.  If you have more complicated scenarios like one thread
communicating with multiple other threads in a selective fashion you may
also be interested in software transactional memory (STM).

If you are using separate threads to perform calculations, you should
make sure that you only pass fully evaluated values.  In many cases it
suffices to evaluate to WHNF, in which case you can simply write:

    putMVar var $! x

This writes the WHNF of 'x' to the MVar 'var'.  If the values you pass
around are of more complicated data types with non-strict parts (like
(Integer, Integer) instead of just Integer), you can also evaluate to
NF:

    import Control.DeepSeq

    putMVar var $!! x

Another option is go without concurrency entirely.  Since this is about
parallel calculations, I suppose that your computations are actually
pure.  Let me give you an example:

    let xs :: [Integer]
        xs = map (^1000000) [2..1000]
    mapM_ print xs

To parallelize this you can simply use parallel strategies:

    import Control.Parallel.Strategies

    let xs :: [Integer]
        xs = parMap rseq (^1000000) [2..1000]
    mapM_ print xs

This calculates the list values in parallel and is as simple as
replacing "map" by "parMap rseq" or "parMap rdeepseq" (if the elements
have non-strict parts like (Integer, Integer) instead of just Integer).

Remember that for pure values you can always just say, "please evaluate
this in parallel".  No need at all to mess around with threads.


Greets,
Ertugrul

-- 
Not to be or to be and (not to be or to be and (not to be or to be and
(not to be or to be and ... that is the list monad.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: not available
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20130126/4ac7b484/attachment.pgp>


More information about the Haskell-Cafe mailing list