Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Program crashing when trying to create multiple threads

I have the following program:

module Main where

import System (getArgs)
import Control.Concurrent
import Control.Monad

spawn left id = do
   right <- newEmptyMVar
   forkIO (thread id left right) 
   return right

thread id left right = go 
   where go = do l <- takeMVar left
                 putStrLn (show id)
                 putMVar right ()

main = do
   args <- getArgs
   if null args then
      putStrLn "Arguments not supplied"
   else do
      initial <- newEmptyMVar
      final <- foldM spawn initial [1..(read (head args))]
      putMVar initial ()
      takeMVar final

As you can see, it just creates a bunch of threads: each thread prints an integer, but the second thread waits for the first before printing, the third waits for the second and so on. Let us not discuss the usefulness of this program (it's just an exercise).

Now, when I try to create one million threads, the program is killed with SIGKILL. I'd like to know the reason of this. Is it because of too many MVars?

Thanks.


1 Answers

Every thread that's created requires its own program stack. I don't actually know how large of a stack Haskell uses for its threads, but if it's 4kbytes (which would be terribly small, actually) that's going to be 4GB just for the million stacks. If you're on a 32-bit machine, that's all of addressable memory, so that's obviously not going to work. And typical stack sizes are more like a megabyte!

like image 150
Ernest Friedman-Hill Avatar answered Jun 06 '26 05:06

Ernest Friedman-Hill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!