Is there a way in Haskell to query thread state using ThreadID after a forkIO?
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.Concalive :: ThreadID -> IO Boolalive = 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.Concimport Control.MonadisThreadStatusBlocked :: ThreadStatus -> BoolisThreadStatusBlocked (ThreadBlocked _) = TrueisThreadStatusBlocked _ = FalseisAlive :: ThreadId -> IO BoolisAlive = fmap (liftM2 (||) (ThreadRunning ==) isThreadStatusBlocked) . threadStatus