What is a reliable way to check if a thread is working?

I am currently using essentially the following code to start workflows.

import Control.Monad      (void)
import Control.Concurrent (forkIO)
import Control.Exception  (finally)
import Data.IORef         (newIORef, writeIORef, readIORef)

startWorker :: IO a -> IO (IO Bool)
startWorker work = do
    running <- newIORef True
    _ <- forkIO $ void work `finally` writeIORef running False
    return $ readIORef running

those. start doing some work in the background and return an IO action that allows the caller to be polled if the workflow is still running, or if it has stopped for some reason.

How reliable is this method? Are there situations where a thread would die without calling a block finally(except, of course, a situation where the whole process was killed)? Is there a better way to achieve the same functionality?

+4
source share
2 answers

async , , "void work` finally` writeIORef running False". forkFinally, .

, . async. . poll, Async.

+7

Yuras , forkIO , , , :

, , forkIO, forkFinally. , forkIO (x finally y), forkFinally x (\_ -> y). , API Async, .

+5

Source: https://habr.com/ru/post/1533894/


All Articles