Program crashes 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, etc. Let's not discuss the usefulness of this program (this is just an exercise).

Now, when I try to create a million threads, the program will be killed using SIGKILL. I would like to know the reason for this. Is it due to too many MVars?

Thank.

+3
source share
2 answers

. , Haskell , 4kbytes ( , ), 4 . 32- , , , , . !

+2

GHC 1K, 8M .

, RTS -k -k, :

$ ./Threads 1000000 +RTS -k512 -K1K -s

(64- 6 ), 2 .

   4,743,629,168 bytes allocated in the heap
   4,368,720,328 bytes copied during GC
   1,043,256,808 bytes maximum residency (11 sample(s))
     221,352,512 bytes maximum slop
            2413 MB total memory in use (0 MB lost due to fragmentation)

  Generation 0:  8707 collections,     0 parallel,  1.46s,  1.59s elapsed
  Generation 1:    11 collections,     0 parallel,  1.72s,  3.16s elapsed

  INIT  time    0.00s  (  0.00s elapsed)
  MUT   time    5.86s  ( 15.76s elapsed)
  GC    time    3.18s  (  4.75s elapsed)
  EXIT  time    0.08s  (  0.08s elapsed)
  Total time    9.12s  ( 20.59s elapsed)

  %GC time      34.9%  (23.1% elapsed)

  Alloc rate    798,590,769 bytes per MUT second

  Productivity  65.1% of total user, 28.9% of total elapsed

./Threads 1000000 +RTS -K1K -s  9.12s user 3.92s system 62% cpu 20.815 total
+2

All Articles