11
import Control.Concurrent
main = do
    forkIO $ putStrLn "123"
    forkIO $ putStrLn "456"

I have written the code above. But when I executed it, I always got 123 only. 456 is not printed. I guess it is because main thread ended before the other thread so the whole program just ended.

How can I prevent this? Any api can make sure main thread ended after all threads ended?

OS: OS X 10.8.3

compiler: ghc 7.4.2

4

2 回答 2

16

使用async库:

import Control.Concurrent.Async

main = do
    a1 <- async $ putStrLn "123"
    a2 <- async $ putStrLn "456"
    mapM_ wait [a1, a2]

这相当于丹尼尔的解决方案,除了有两个小优点:

  • 它确保在分叉线程中引发的任何异常都会在父线程中重新引发,而不会导致死锁
  • 更方便
于 2013-05-22T19:27:24.903 回答
9
import Control.Concurrent
main = do
    done <- newEmptyMVar
    forkIO $ putStrLn "123" >> putMVar done ()
    forkIO $ putStrLn "456" >> putMVar done ()
    takeMVar done
    takeMVar done
    -- OR: replicateM_ 2 (takeMVar done)
于 2013-05-22T18:36:01.817 回答