gpt4 book ai didi

multithreading - 如何使用安全异常库捕获异步异常?

转载 作者:行者123 更新时间:2023-12-03 13:03:11 31 4
gpt4 key购买 nike

我正在尝试使用 Haskell 构建并发且健壮的代码,建议我使用 safe-exceptionsasync图书馆。但是,我很难理解如何处理 async 中抛出的非 fatal error 。行动。

例如,如果有一个简单的循环每隔 n 秒检查一次网络资源,那么使用 cancel 停止它是有意义的。会导致 AsyncCancelled 的函数在单独的线程中抛出异常。当然,也有可能是 IOError由于网络出现故障或其他问题,将从线程内抛出。根据异常的类型及其包含的数据,我想控制单独的线程是否忽略异常、执行某些操作、停止或在主线程中引发异常。

使用安全异常库,唯一能够做到这一点的函数是catchAsync。和其他类似的,在文档中被标记为危险。除此之外,还有waitCatch在异步库中,但 fromException函数总是返回 Nothing当我尝试提取 IOError :

{-# LANGUAGE ScopedTypeVariables #-}

import Control.Concurrent.Async
import Control.Concurrent hiding (throwTo)
import Control.Exception.Safe
import Control.Monad
import System.IO
import System.IO.Error hiding (catchIOError)

main = do
hSetBuffering stdin NoBuffering
putStrLn "Press any key to continue..."
a <- async runLoop
async $ hWaitForInput stdin (-1) *>
throwTo (asyncThreadId a) (userError "error")
waitCatch a >>= either handler nothing
where
printThenWait i = putStr (show i ++ " ") *> threadDelay 1000000
runLoop = sequence_ $ printThenWait <$> [1..]
nothing _ = pure ()
handler e
| Just (e' :: IOError) <- fromException e =
putStrLn "It's an IOError!"
| (Nothing :: Maybe IOError) <- fromException e =
putStrLn "We got Nothing!"

我对从异步异常中恢复的危险感到有点困惑,尤其是当标准函数如 cancel 时。导致它们被抛出,我不知道在使用这两个库时推荐的处理它们的方法是什么。这是 catchAsync 的实例吗?会被推荐,还是有另一种方法来处理我没有发现的这些类型的情况?

最佳答案

请注意 Control.Exception.Safe.throwTo wraps同步异常到 AsyncExceptionWrapper , 和 IOError 同步。 (我不知道为什么这种包装是必要的,无论如何你都不应该异步抛出同步异常。)

要使您的代码正常工作,您应该捕获 AsyncExceptionWrapper或使用 Control.Exception.throwTo .但实际上我并不完全理解你想要做什么,很可能你把事情复杂化了。

关于multithreading - 如何使用安全异常库捕获异步异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50581476/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com