title: Haskell forkIO threads writing on top of each other with putStrLn
body: <p>I was playing around with Haskell lightweight threads (<code>forkIO</code>) with the following code:</p>
  
  <pre><code>import Control.Concurrent
  
  beginTest :: IO ()
  beginTest = go
      where
      go = do
          putStrLn "Very interesting string"
          go
          return ()
  
  main = do
      threadID1 &lt;- forkIO $ beginTest
      threadID2 &lt;- forkIO $ beginTest
      threadID3 &lt;- forkIO $ beginTest
      threadID4 &lt;- forkIO $ beginTest
      threadID5 &lt;- forkIO $ beginTest
  
      let tID1 = show threadID1
      let tID2 = show threadID2
      let tID3 = show threadID3
      let tID4 = show threadID4
      let tID5 = show threadID5
  
      putStrLn "Main Thread"
      putStrLn $ tID1 ++ ", " ++ tID2 ++ ", " ++ tID3 ++ ", " ++ tID4 ++ ", " ++ tID5
      getLine
      putStrLn "Done"
  </code></pre>
  
  <p>Now the expected output to this would be a whole bunch of these:</p>
  
  <pre><code>Very interesting string
  Very interesting string
  Very interesting string
  Very interesting string
  </code></pre>
  
  <p>with one of these somewhere in there:</p>
  
  <pre><code>Main Thread
  </code></pre>
  
  <p>However, the output (or first several lines anyway) turned out to be this:</p>
  
  <pre><code>Very interesting string
  Very interesting string
  Very interesting string
  Very interesting string
  Very interesting string
  Very interesting string
  Very interesting string
  Very interesting string
  Very interesting string
  Very interesting string
  Very interesting string
  Very interesting string
  Very interesting string
  Very interesting string
  Very interesting string
  Very interesting string
  Very interesting string
  Very interesting string
  Very interesting string
  Very VVVViMeeeenarrrrtiyyyyen    r iiiieTnnnnshtttttreeeeierrrrnaeeeegdssss 
  ttttsiiiitTnnnnrhggggir    nessssgatttt
  drrrrIiiiiVdnnnne ggggr5
  
  
  
  y1 ,VVVVi eeeenTrrrrthyyyyer    reiiiieannnnsdtttttIeeeeidrrrrn eeeeg5ssss 2tttts,iiiit nnnnrTggggih    nrssssgetttt
  arrrrdiiiiVInnnnedggggr 
  
  
  
  y5 3VVVVi,eeeen rrrrtTyyyyeh    rriiiieennnnsatttttdeeeeiIrrrrndeeeeg ssss 5tttts4iiiit,nnnnr ggggiT    nhssssgrtttt
  errrraiiiiVdnnnneIggggrd
  
  
  
  y  5VVVVi5eeeen
  rrrrtyyyye    riiiiennnnsttttteeeeirrrrneeeegssss ttttsiiiitnnnnrggggi    nssssgtttt
  rrrriiiiVnnnneggggr
  
  
  
  y VVVVieeeenrrrrtyyyye    riiiiennnnsttttteeeeirrrrneeeegssss ttttsiiiitnnnnrggggi    nssssgtttt
  rrrriiiiVnnnneggggr
  </code></pre>
  
  <p>Every few lines the text would shift, though it's pretty clear that the <code>Very interesting string</code>s ended up on top of each other, because somehow the threads using <code>putStrLn</code> at the same time ended up writing to stdout on top of each other. Why is this, and how (without resorting to message passing, timing, or some other overcomplicated and convoluted solution) can it be overcome?</p>