Lazy IO and asynchronous callbacks?
J. Garrett Morris
jgmorris at cs.pdx.edu
Thu Jul 8 18:25:53 EDT 2010
I'm currently in the process of wrapping a C API, and I've run across
an interesting possibility. Basically, the C API exposes non-blocking
versions of some potentially long-running operations, and will invoke
a callback to indicate that the long running operation has finished.
For instance, I have something like:
int longRunningReadOperation(int length, byte * buf, void (*callback)())
When callback is called, then there are length bytes in buf. What I'd
like to do is wrap this in Haskell function like:
longRunningReadOperation :: Int -> IO [Byte]
such that the function returns immediately, and only blocks when
someone pulls on the results if the callback hasn't been triggered
yet. I figure I'm going to need unsafeInterleaveIO, but I'm not sure
what to do in the computation I pass to it. I had a small hope that
if the callback put the results into an MVar (say var), and I returned
(unsafeInterleaveIO (readMVar var)) that might work, but it seems like
if the readMVar blocks then the callback doesn't execute either. This
doesn't surprise me, but it does leave me needing another option. I
don't see a way to get the callback into a new Haskell thread, so that
it can do the putMVar from there... am I missing something obvious?
Thanks in advance!
More information about the Glasgow-haskell-users