Created
July 26, 2022 12:35
-
-
Save viviag/107782396a0809acbac09123a0c4155c to your computer and use it in GitHub Desktop.
Count active threads in order to terminate gracefully, minimal version
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Main where | |
import GHC.Conc (atomically) | |
import System.Exit (exitSuccess) | |
import Control.Concurrent.STM.TVar (TVar, readTVarIO, newTVarIO, modifyTVar') | |
import Control.Concurrent (forkIO, threadDelay) | |
import Control.Exception (bracket_) | |
import Control.Monad (void, when, forever) | |
import Data.Int | |
fork :: TVar Int64 -> IO () -> IO () | |
fork sem = void . forkIO . bracket_ | |
(atomically $ modifyTVar' sem (+1)) | |
(atomically $ modifyTVar' sem (subtract 1)) | |
wait :: TVar Int64 -> IO () | |
wait sem = forever $ do | |
threadDelay 1000 | |
value <- readTVarIO sem | |
when (value == 0) $ exitSuccess | |
action :: IO () | |
action = do | |
putStrLn "Enter" | |
threadDelay 10000 | |
putStrLn "Exit" | |
main :: IO () | |
main = do | |
sem <- newTVarIO 0 | |
fork sem action | |
fork sem action | |
wait sem |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment