feature request: tear-down of child threads
Hi everybody,
I just figured out how to send ThreadKilled signals to all child threads. The use case is that we have lots of parallel threads that work on a database, and if they are killed they want to record that fact to the database before being destroyed. Since the child threads don't get notified if the main thread receives a user interrupt, I did something like this:
worker :: ThreadId -> MVar (Set ThreadId) -> Int -> IO ()
worker mainTid globalState _ =
do
workerThreadId <- myThreadId
modifyMVar_ globalState (\ s -> return $ S.insert workerThreadId s)
finally
(sequence_ $ replicate 7 (print workerThreadId >> threadDelay (1 * 10^6)))
(print $ "done: " ++ show workerThreadId)
main = do
mainTid <- myThreadId
globalState :: MVar (Set ThreadId) <- newMVar S.empty
catch
(do
exceptions <- parallelE_ (L.map (worker mainTid globalState) [1..3])
print exceptions)
(\ (e :: SomeException) -> do
workerThreadIds <- S.toList <$> readMVar globalState
mapM_ (\ tid -> throwTo tid ThreadKilled) workerThreadIds
print e)
stopGlobalPool
Without this, if the main thread dies, the child threads are just silenlty destroyed without having a chance to do anything about it (write the fact to a log file, roll back a transaction, ...). I suspect that many people have been forced to figure this out and implement it by hand, and it would be cool if it could be stashed away in parallel-io under the hood.
Questions: (a) would a patch that does this implicitly be welcome? (b) would it be done like in the code I just hacked together, or would you like to see it done differently? (c) is there any concievable reason anybody would want to switch this feature off?