× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Haskell, Channels, STM, -threaded, Message Passing

Carsten König
Jul 17, 2015
<p>No your idea is right - this is kindof what <code>TChan</code>s are for - you just missed a minor point of <code>forkIO</code>:</p> <p>The problem is that your main thread will not wait for the termination of the threads created with <code>forkIO</code> (<a href="https://hackage.haskell.org/package/base-">see here for reference</a>)</p> <p>so if I use the <em>hint</em> given in the reference:</p> <pre><code>import Control.Concurrent import Control.Concurrent.STM p :: Num a =&gt; TChan a -&gt; IO () p chan = do atomically $ writeTChan chan 1 atomically $ writeTChan chan 2 q chan = do msg1 &lt;- atomically $ readTChan chan msg2 &lt;- atomically $ readTChan chan -- for testing purposes putStrLn $ show msg1 putStrLn $ show msg2 main :: IO () main = do children &lt;- newMVar [] chan &lt;- atomically $ newTChan _ &lt;- forkChild children $ p chan _ &lt;- forkChild children $ q chan waitForChildren children return () waitForChildren :: MVar [MVar ()] -&gt; IO () waitForChildren children = do cs &lt;- takeMVar children case cs of [] -&gt; return () m:ms -&gt; do putMVar children ms takeMVar m waitForChildren children forkChild :: MVar [MVar ()] -&gt; IO () -&gt; IO ThreadId forkChild children io = do mvar &lt;- newEmptyMVar childs &lt;- takeMVar children putMVar children (mvar:childs) forkFinally io (\_ -&gt; putMVar mvar ()) </code></pre> <p>it works as expected:</p> <pre><code>d:/Temp $ ghc --make -threaded tchan.hs [1 of 1] Compiling Main ( tchan.hs, tchan.o ) Linking tchan.exe ... d:/Temp $ ./tchan.exe 1 2 d:/Temp $ </code></pre> <p>and of course it will continue to work if you switch the calls to <code>p</code> and <code>q</code> too</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/30340159/Haskell,%20Channels,%20STM,%20-threaded,%20Message%20Passing/30340326">Stack Overflow</a>.</p>
comments powered by Disqus