Cetin Sert
Cetin Sert

Reputation: 4600

Is there a way in Haskell to query thread state using ThreadID after a forkIO?

What I am looking for is a simple function of type:

alive :: ThreadID -> IO Bool

Upvotes: 10

Views: 739

Answers (2)

MasterMastic
MasterMastic

Reputation: 21306

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

Upvotes: 1

dflemstr
dflemstr

Reputation: 26177

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

Upvotes: 16

Related Questions