Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 799
Cetin Sert Avatar asked Feb 28 '12 02:02

Cetin Sert


2 Answers

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
like image 93
dflemstr Avatar answered Nov 20 '22 13:11

dflemstr


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
like image 1
MasterMastic Avatar answered Nov 20 '22 13:11

MasterMastic