What I am looking for is a simple function of type:
alive :: ThreadID -> IO Bool
This is not possible with the standard base
libraries as far as I know, but you can use the GHC specific API to get a thread's status:
import GHC.Conc
alive :: ThreadID -> IO Bool
alive = fmap (== ThreadRunning) . threadStatus
Different definition extending on dflemstr's answer to also account for when the thread is blocked. I think it also counts as alive, as pretty soon it's executing code again, once the reason for why it's blocked is taken care of (e.g. an MVar
is written to, an STM
transaction on retry
completes, etc.):
import GHC.Conc
import Control.Monad
isThreadStatusBlocked :: ThreadStatus -> Bool
isThreadStatusBlocked (ThreadBlocked _) = True
isThreadStatusBlocked _ = False
isAlive :: ThreadId -> IO Bool
isAlive = fmap (liftM2 (||) (ThreadRunning ==) isThreadStatusBlocked) . threadStatus
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With