Skip to content

Instantly share code, notes, and snippets.

@osa1
Last active August 22, 2018 05:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save osa1/dece072bda08f1791651b86518d433c1 to your computer and use it in GitHub Desktop.
Save osa1/dece072bda08f1791651b86518d433c1 to your computer and use it in GitHub Desktop.
{-# LANGUAGE ForeignFunctionInterface #-}
module Main where
import System.Clock -- clock
import Foreign.C.Types -- base
foreign import ccall unsafe "my_sleep" sleep_unsafe :: CInt -> IO CInt
foreign import ccall safe "my_sleep" sleep_safe :: CInt -> IO CInt
{-# NOINLINE sleep_unsafe_wrap #-}
{-# NOINLINE sleep_safe_wrap #-}
sleep_unsafe_wrap, sleep_safe_wrap :: CInt -> IO CInt
sleep_unsafe_wrap i = sleep_unsafe i
sleep_safe_wrap i = sleep_safe i
timeIt :: IO a -> IO a
timeIt a = do
start <- getTime Monotonic
ret <- a
end <- getTime Monotonic
print (end - start)
return ret
main :: IO ()
main = do
putStrLn "Running safe"
i1 <- timeIt (sleep_safe_wrap 1000)
putStrLn "Running unsafe"
i2 <- timeIt (sleep_unsafe_wrap 1000)
print i1
print i2
#include <unistd.h>
#include <stdio.h>
int my_sleep(int seconds)
{
printf("Sleeping for %d seconds\n", seconds);
sleep(seconds);
return seconds;
}
@bgamari
Copy link

bgamari commented Aug 21, 2018

To quote sleep(3):

sleep() causes the calling thread to sleep either until the number of real-time seconds specified in seconds have elapsed or until a signal arrives which is not ignored.

I would imagine this isn't sleeping because a signal arrives (perhaps a timer signal for GHC's itimer). This is why sleep returns the duration is waited for.

@osa1
Copy link
Author

osa1 commented Aug 22, 2018

Interesting, thanks @bgamari. Indeed when I print return values of sleep I can see that they can't really sleep probably because of a signal. I'll try masking signals and see if that works.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment