hClose non-terminating

George Russell ger at tzi.de
Thu Nov 6 06:49:21 EST 2003


Simon Marlow wrote (snipped):

> The thread reading from the handle has a lock on it, so that hClose has
> to wait before it can gain access to the handle to close it.

OK, so it isn't a bug but expected behaviour that if you have one thread
doing hGetChar on a handle, an attempt to close the handle in another thread
will not terminate.  But it seems to me at least a gotcha, which should
be documented somewhere.  The trouble is that (a) it's quite common to have
a thread somewhere dedicated to monitoring the output of some handle;
(b) I at least have up to now assumed that hClose, like the C low-level (f)close
functions, is something that basically can't fail or block, and so you never need
to worry about calling it to clean-up.

> What would you like to happen in this case?  I guess getChar could be
> given an exception if the handle was closed underneath it.  The problem
> is that releasing the lock in the middle of getChar while it waits for
> input is quite awkward to implement, and doing it in the middle of
> getLine is even worse.

I think raising an exception during getChar would be best.

However if not, what then?  It seems as if hClose has two tasks (1) flushing
any remaining output; (2) freeing any remaining datastructures, fds required for
reading or writing.  (1) can be done immediately.  Perhaps if (2) is impossible
to do right now because a getChar is sitting on the lock, you could fork a thread
to do it?  After all it's not so important if it doesn't get done at all.

> My feeling is that this would be a pain to fix.  Can you work around it?

Yes, I can work around it.  Perhaps GHC needs a page in the documentation
somewhere about gotchas in IO & concurrency.  (Another one would be
the way getChar stops the world on Windows, unless Sigbjorn has fixed that
yet.)

thanks Simon,

George



More information about the Glasgow-haskell-bugs mailing list