The following program creates two threads at the same time, each of which sleeps for an arbitrary period of time before printing a line of text into standard output.
import Control.Concurrent import Control.Monad import System.Random randomDelay t = randomRIO (0, t) >>= threadDelay printer str = forkIO . forever $ do randomDelay 1000000 -- μs putStrLn str main = do printer "Hello" printer "World" return ()
The output usually looks something like
>> main Hello World World Hello WoHrelld o World Hello *Interrupted >>
How do you guarantee that only one thread can write to stdout at a time? It looks like STM should be fine, but all STM transactions must be of type STM a for some a , and the action that is printed on the screen is of type IO a , and there seems to be no way to insert IO into STM .
multithreading haskell stm
Chris taylor
source share