
Maurício wrote:
Hi,
After I have spawned a thread with 'forkIO', how can I check if that thread work has finished already? Or wait for it?
Thanks, Maurício
The best way to do this is using Control.Exception.finally:
myFork :: IO () -> IO (ThreadId,MVar ()) myFork todo = m <- newEmptyMVar tid <- forkIO (finally todo (tryPutMVar m ())) return (tid,m)
No other part of the program should write to the MVar except the finally clause. The rest of the program can check (isEmptyMVar m) as a non-blocking way to see if the thread is still running. Or use (swapMVar m ()) as a way to block until the MVar has been filled as a way of blocking until the thread is finished. These techniques are needed because forkIO is a very lightweight threading mechanism. Adding precisely the features you need makes for good performance control, as seen in the great computer language shootout benchmarks. Cheers, Chris