首页 > 解决方案 > Haskell async:在 withAsync 中使用不同类型的 Monad

问题描述

我正在编写一个 Monad 转换器,并且要运行转换器,我需要生成一个 IO 线程,该线程将元素写入主线程可以访问的 TQueue。但是,没有一个 withAsync 版本提供正确的签名。我需要一个带有签名的东西

(MonadIO m) => IO a -> (Async a -> m b) -> m b

我尝试了提升异步,但这有很多限制,并且在同一个 Monad 中有主线程和衍生线程。

或者,由于 Control.Concurrent.Async 说 withAsync 相当于

withAsync action inner = mask $ \restore -> do
    a <- async (restore action)
    restore (inner a) `finally` uninterruptibleCancel a

另一种解决方案是具有类型签名的掩码版本,例如

mask :: (MonadMask m) => ((forall a n. (MonadMask n) => n a -> n a) -> m b) -> m b

我最接近解决方案的是以下代码,我很确定它不起作用,但我不能确定,因为我不完全理解掩码是如何工作的。

withAsyncT :: (MonadIO m, MonadMask m) => IO a -> (Async a -> m b) -> m b
withAsyncT action inner = mask $ \restore -> do
     a <- liftIO $ asyncWithUnmask (\rstr -> rstr action)
     restore (inner a) `finally` (liftIO $ uninterruptibleCancel a)

是否有合理的解决方案来获得这样的 withAsync?还是我必须使用 unliftio 之类的东西?

标签: haskellasynchronousexceptionmonad-transformersstm

解决方案


推荐阅读