I would like to optionally abort a getChar
action.
I need the following function:
getChar' :: (Char -> IO ()) -> IO (IO ())
In case of abort <- getChar' callback
, a character is read from standard input, unless abort
is called before a character is available.
If a character is read, callback
is called with it.
I have the following prototype implementation:
import Control.Monad
import Control.Concurrent
getChar' :: (Char -> IO ()) -> IO (IO ())
getChar' callback = do
v <- newEmptyMVar
tid <- forkIO $ do
c <- getChar
b <- tryPutMVar v ()
when b $ callback c
return $ do
b <- tryPutMVar v ()
when b $ killThread tid
The problem is that killThread
may abort the thread after reading the char but before putting ()
into the MVar.
I have no idea how to solve this problem, is it possible at all with the base package? If not, have you seen a similar function implemented in other packages?