为什么在以下代码中会立即返回?
{-# 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
$ ghc --make Sleep.hs && ./Sleep [1 of 1] Compiling Main ( Sleep.hs, Sleep.o ) Linking Sleep ... 29448.191603秒 10 29448.20158秒 29458.211402秒 $ 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
注意:实际上,我想在C代码中使用 sleep
函数来模拟一些耗时的计算,并在Haskell中调用该函数,但这也不起作用,可能是因为相同的原因。
sleep
的信号。您是否检查了错误代码?也许您应该将其包装在循环中,以便在被中断时重新启动它(在这种情况下,最好使用nanosleep
来获得更高的精度)。 - Rufflewindsleep
不会返回错误代码,但会返回未休眠的秒数。尚未尝试nanosleep
,但usleep
也无效。 - Zetaerrno
变量“返回”。将(c_sleep 10)
包装在throwErrnoIf (/= 0) "sleep"
中,你会发现它被中断了。 - Rufflewindsleep
调用。 - Rufflewindman 3 sleep
没有提到errno
的更新?我想我得写一个void nanosleep_loop(uint32_t)
,因为nanosleep
也会受影响。票据可能已经回答了这个问题,所以请随意添加一个。 - Zetasleep
的文档根本没有提到errno
(我看的是nanosleep
)。不过,文档确实说如果返回值为非零,则是由于被信号中断。 - Rufflewind