我有一个工作线程,它从 MVar 重复读取数据并对其执行一些有用的工作。一段时间后,程序的其余部分会忘记该工作线程,这意味着它将等待空的 MVar 并变得非常孤独。我的问题是:
Will the MVar be garbage collected if threads no longer write to it, for instance because they all wait for it? Will garbage collection kill the waiting threads? If neither, can I somehow indicate to the compiler that the MVar should be garbage collected and the thread be killed?
编辑:我可能应该澄清我的问题的目的。我不想要针对僵局的一般保护;相反,我想做的是将工作线程的生命周期与值的生命周期联系起来(例如:死值由垃圾收集声明)。换句话说,工作线程是一种资源,我不想手动释放它,而是在某个值(MVar 或导数)被垃圾收集时释放。
这里是一个示例程序,演示了我的想法
import Control.Concurrent
import Control.Concurrent.MVar
main = do
something
-- the thread forked in something can be killed here
-- because the MVar used for communication is no longer in scope
etc
something = do
v <- newEmptyMVar
forkIO $ forever $ work =<< takeMVar v
putMVar v "Haskell"
putMVar v "42"
换句话说,我希望当我无法再与其通信时,即当用于通信的 MVar 不再在范围内时,该线程被终止。如何做到这一点?
最佳答案
它会正常工作:当 MVar
只能由被阻塞的线程访问时,就会向该线程发送 BlockedIndefinitelyOnMVar
异常,这通常会导致它会默默地死掉(线程的默认异常处理程序会忽略此异常)。
顺便说一句,为了在线程终止时进行一些清理,您需要使用 forkFinally
(我 just added 到 Control.Concurrent
)。
关于haskell - 当 MVar 被垃圾回收时终止线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10871303/