Cogs and Levers A blog full of technical stuff

Simple forkIO Usage

Creating new threads in Haskell is quite easy (once you know how). Here’s a simple snippet for using forkIO and myThreadId to get you started.

module Main where

import Control.Concurrent

main :: IO ()
main = do
    -- grab the parent thread id and print it
    parentId <- myThreadId
    putStrLn (show parentId)
    
    -- create a new thread (ignore the return)
    _ <- forkIO $ do
      -- grab the child thread id and print it
      childId <- myThreadId
      putStrLn (show childId)
      
    return ()