为什么不睡觉?

Zet*_*eta 16 haskell ffi ghc

为什么c_sleep在以下代码中立即返回?

{-# LANGUAGE ForeignFunctionInterface #-}
import Foreign.C.Types
import Data.Time.Clock
import Control.Concurrent

foreign import ccall unsafe "unistd.h sleep" 
    c_sleep :: CUInt -> IO CUInt

main :: IO ()
main = do
    getCurrentTime >>= print . utctDayTime
    c_sleep 10     >>= print                -- this doesn't sleep
    getCurrentTime >>= print . utctDayTime
    threadDelay $ 10 * 1000 * 1000          -- this does sleep
    getCurrentTime >>= print . utctDayTime
Run Code Online (Sandbox Code Playgroud)
$ ghc --make Sleep.hs && ./Sleep
[1 of 1] Compiling Main             ( Sleep.hs, Sleep.o )
Linking Sleep ...
29448.191603s
10
29448.20158s
29458.211402s

$ ghc --version
The Glorious Glasgow Haskell Compilation System, version 7.8.3

$ cabal --version
cabal-install version 1.20.0.3
using version 1.20.0.0 of the Cabal library 

注意:实际上,我想sleep在C代码中使用模拟函数中的一些繁重计算func并在Haskell中调用函数,但这也不起作用,可能是出于同样的原因.

Ruf*_*ind 12

GHC的RTS似乎将信号用于其自身 目的,这意味着它不会在睡眠被这些信号之一中断之前很久.我不认为它也是一个错误,运行时确实带有它自己的领域,可以这么说.Haskellian的方法是使用,threadDelay但如果没有一些技巧,C程序就不容易访问它.

正确方法是重复恢复睡眠,尽管其它信号的干扰.我建议使用,nanosleep因为sleep只有几秒的精度,信号似乎比这更频繁地发生.

#include <errno.h>
#include <time.h>

/* same as 'sleep' except it doesn't get interrupted by signals */
int keep_sleeping(unsigned long sec) {
    struct timespec rem, req = { (time_t) sec, 0 }; /* warning: may overflow */
    while ((rem.tv_sec || rem.tv_nsec) && nanosleep(&req, &rem)) {
        if (errno != EINTR) /* this check is probably unnecessary */
            return -1;
        req = rem;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)