haskell - 当 MVar 被垃圾回收时终止线程

标签 haskell concurrency garbage-collection

我有一个工作线程,它从 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 addedControl.Concurrent)。

关于haskell - 当 MVar 被垃圾回收时终止线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10871303/

相关文章:

haskell - 在另一个字符串 Haskell 中查找子字符串的索引

haskell - 通过 List Monad 模拟非确定性选择

haskell - 如何对列表列表的相同索引求和?

multithreading - 是否因为 “lock”而没有使用 “cache coherency mechanism”操作码前缀?

asynchronous - CUDA 流、纹理绑定(bind)和异步 memcpy

java - 如何确保单个 Runnable 任务不会在两个线程上同时运行

haskell - 重大变化在哪里?

c# - 同一类的析构函数中的对象实例化和垃圾收集

android - 如何判断哪些线程产生了所有垃圾?

java - JNI 中的 GlobalReferences 是否会阻止 GC 清理对象?