代码之家  ›  专栏  ›  技术社区  ›  Bercovici Adrian

如何在超时时重试阻止IO操作?

  •  2
  • Bercovici Adrian  · 技术社区  · 6 年前

    如何处理阻塞 IO 在哈斯克尔的行动?我怎么能把这个 输入输出 abort 如果我不能在可配置的时间内得到结果。(定时器在外部。)

    retries 假设我想表演 输入输出 输入输出 在超时作用域中的操作,以便在超时过期后调用它,如果且仅当 重试次数 大于0。

    输入输出 像行动一样 ioMethod::IO String (我还没有在socket库中查找Haskell),我们假设它是一个黑盒,

    module Retry where
    
    import IOExternal(ioMethod)
    
    retryFunc :: Int -> IO String
    retryFunc retries=do
                msg<-retry 5 100 IOExternal 
                return msg
    
    retry :: Int -> Int -> IOExternal -> IO String
    retry retries timeout ioMethod = go retries timeout "" where
            go 0       timeout ioMethod  msg =
                        if msg=="" then return "Max Retries reached" 
                                   else return msg
    
            go retries timeout ioMethod  msg counter
                   = gogo retries timeout counter msg  where
                         gogo retries timeout 0 msg = return ""
                         gogo retries timeout counter msg
                            = ioMethod>>=gogo retries timeout counter-1 
    

    我不知道如何模拟这最后一个条件/行。

    附笔 我还不熟悉Haskell(这里是初学者)中的线程,我确实认为超时作用域应该在不同的线程中执行,不知何故,我需要从主程序中检查它,或者重新调用它(如果重试>0),或者结束主方法。

    1 回复  |  直到 6 年前
        1
  •  3
  •   Daniel Wagner    6 年前

    你可以用 timeout

    retry :: Int -> Int -> IO a -> IO (Maybe a)
    retry 0 _ _ = return Nothing
    retry numRetries microseconds action = do
        result <- timeout microseconds action
        case result of
            Nothing -> retry (numRetries-1) microseconds action
            Just a  -> return (Just a)
    

    不过,一定要阅读文档,了解有关FFI的注意事项。