module Control.Event.Relative
( EventId
, addEvent
, delEvent
) where
import Prelude hiding (catch)
import Control.Concurrent
import Control.Exception
import Control.Monad (when)
import Control.Concurrent.MVar
type EventId = (ThreadId, MVar Bool)
addEvent :: Int -> IO () -> IO EventId
addEvent delay event = do
m <- newMVar False
t <- forkIO (eventThread m)
return (t,m)
where
eventThread m = do
threadDelay delay
forkIO $ runThread m
return ()
runThread m = do
b <- swapMVar m True
when (not b) event
delEvent :: EventId -> IO Bool
delEvent (t,m) = do
b <- takeMVar m
when (not b) (killThread t)
putMVar m True
return (not b)