May I limit memory usage per function/monad/thread in Haskell? May I limit memory usage per function/monad/thread in Haskell? multithreading multithreading

May I limit memory usage per function/monad/thread in Haskell?


In the latest versions of GHC, it is possible to set per-thread allocation counters and limits, using setAllocationCounter and enableAllocationLimit from GHC.Conc. When a limit is set and the counter reaches 0, the thread receives an asynchronous exception.

The counters measure allocation, and not the size of the live set. For example, this code hits the limit, despite its live set never becoming very big:

{-# LANGUAGE NumDecimals #-}module Main whereimport Data.Foldable (for_)import System.IOimport GHC.Conc (setAllocationCounter,enableAllocationLimit)main :: IO ()main =   do setAllocationCounter 2e9     enableAllocationLimit     let writeToHandle h =            for_ ([1..]::[Integer])                 (hPutStrLn h . show)     withFile "/dev/null" WriteMode writeToHandle     return ()

Allocation is a bit crude as a measure, but it can still be useful to detect some "out of control" computations.

This blog post by Simon Marlow goes into more detail.