Why this two function created by forkIO in haskell can't be run one by one?

Viewed 72

I have this prog in windows ghc:

import Control.Concurrent

a=print 1
b=print 2

main=do
 forkIO a
 forkIO b

it can only print 1 in console,Why?

I think the main thread run first,then it create a thread,run function a,print 1,then create another thread,run function b,then print 2

so the console will give me

1 2

1 Answers

Ok, I think I remember something about "a Haskell program ends when the main thread exits". So the main thread is ending before the other threads have had a chance to do their thing. A quick fix is

main = do
    forkIO a
    forkIO b
    threadDelay (10^6)  -- 1 second

A less quick, more correct fix is to use MVars to simulate "joining" a thread -- i.e. waiting until it completes.

Related