Haskell超时分歧计算

Tom*_*akl 5 haskell timeout ghc

我正在尝试在Haskell中编写一个安全的超时评估函数.代码如下

import System.Timeout

compute, compute' :: Int -> Int
compute  i = sum [1..300000 + i]
compute' i = last $ repeat i

timedComp :: Int -> a -> IO (Maybe a)
timedComp timeLeft toCompute =
        timeout timeLeft go
    where
        go = toCompute `seq` return toCompute

main = do
    res <- timedComp 10000 (compute 0)
    print res

    res' <- timedComp 10000 (compute' 0)
    print res'
Run Code Online (Sandbox Code Playgroud)

(我知道我只评价WHNF.)

当我运行main时,我只输出一个Nothing,然后程序挂起.我试图编译并运行程序多线程,但它没有帮助.试用GHC 7.6.3和7.8.3.有什么建议?

chi*_*chi 3

Haskell 线程的 GHC 实现有一个限制:上下文切换仅在分配期间发生。因此,根本不执行分配的紧密循环可能会阻止调度程序运行,从而切换到其他线程。

这是这样的例子之一:compute' i = last $ repeat i看起来好像它正在分配列表单元,但不幸的是,GHC 能够将其优化为一个简单的无限循环,删除所有分配 - GHC Core 看起来大致为f x = f x. 这会触发调度程序的缺点。

里德·巴顿(Reid Barton)建议选择-fno-omit-yields解决这个问题。这会导致GHC不能优化那么多。