Re: [Haskell-cafe] Threads and hGetLine

11 views
Skip to first unread message

Joey Adams

unread,
Apr 29, 2012, 1:51:35 AM4/29/12
to H. M., haskel...@haskell.org
On Sat, Apr 28, 2012 at 2:23 PM, H. M. <h._h...@hotmail.com> wrote:
> There are two threads, one which is waits on input via
> hGetLine
> and another, which should terminate this thread or close this handle.
>
> hClose
> as well as
> killThread
> doesn't seem to work, caused by the fact, that the thread is blocked until input
> is availiable.

What OS? GHC currently doesn't have proper IO manager support for
Windows. On Windows, IO is performed through FFI calls. An FFI call
masks asynchronous exceptions (C code generally doesn't expect to be
interrupted at arbitrary points in time). If another thread tries to
`killThread` the thread waiting for input, the exception will not be
received until the FFI call completes. This means both threads will
hang.

-Joey

_______________________________________________
Haskell-Cafe mailing list
Haskel...@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe

Johannes Waldmann

unread,
May 2, 2012, 2:45:44 PM5/2/12
to haskel...@haskell.org

> There are two threads, one which is waits on input via
> hGetLine
> and another, which should terminate this thread or close this handle.

like this? The trick is to fork the blocking call (hGetLine)
and wait on an MVar. That way, the kill signal can be handled:

{-# language PatternSignatures #-}

import Control.Concurrent
import Control.Concurrent.MVar
import Control.Exception
import System.IO

main = do
pid <- forkIO $ do
s <- wawiter
putStrLn s
threadDelay $ 5 * 10^6
killThread pid

waiter = do
v <- newEmptyMVar
forkIO $ do s <- hGetLine stdin ; putMVar v s
readMVar v `Control.Exception.catch`
\ (e :: AsyncException ) -> return "killed"

PS: and I refuse to use the "ScopedTypeVariables" pragma
since obviously there are no type variables.
Reply all
Reply to author
Forward
0 new messages