Timed iteration try 2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import Control.Concurrent
import Control.Exception

timeoutIterate msec f x = do
    mvar <- newMVar x
    let loop = do
        x <- readMVar mvar
        fx <- evaluate (f x)
        swapMVar mvar fx
        loop
    thread <- forkIO loop
    threadDelay msec
    u <- takeMVar mvar
    killThread thread
    return u

Timed iteration try 3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import Control.Concurrent
import Control.Exception
import Data.IORef

timeoutIterate msec f x = do
    ref <- newIORef x
    let loop = do
        x <- readIORef ref
        evaluate (f x) >>= writeIORef ref
        loop
    thread <- forkIO loop
    threadDelay msec
    u <- readIORef ref
    killThread thread
    return u