Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature request: tear-down of child threads #5

Open
mf59816 opened this issue Feb 20, 2013 · 0 comments
Open

feature request: tear-down of child threads #5

mf59816 opened this issue Feb 20, 2013 · 0 comments

Comments

@mf59816
Copy link

mf59816 commented Feb 20, 2013

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant