forkFinally的Haskell类型错误我无法解决

时间:2013-03-14 21:29:02

标签: multithreading haskell network-programming

除了我所犯的错误之外,我还会感激任何有关我所做的事情的提示。

所以我会粘贴代码,它有点;但我认为它主要是是正确的,我只是无法获得forkFinally来键入支票......

错误发生在调用forkFinally的唯一行上:

Ambiguous type variable `e0' in the constraint:
  (Exception e0) arising from a use of `forkFinally'
Probable fix: add a type signature that fixes these type variable(s)
In a stmt of a 'do' block:
  t <- forkFinally (echoHandler a) (exitPool p)
In the expression:
  do { a <- accept s;
       t <- forkFinally (echoHandler a) (exitPool p);
       atomically
       $ do { p' <- readTVar p;
              writeTVar p (t : p') };
       repeatAccept s p }
In an equation for `repeatAccept':
    repeatAccept s p
      = do { a <- accept s;
             t <- forkFinally (echoHandler a) (exitPool p);
             atomically
             $ do { p' <- readTVar p;
                    .... };
             .... } Failed, modules loaded: none.

以下是代码:

type ConnectionHandler = (Handle, HostName, PortNumber) -> IO ()
type Pool = TVar [ThreadId]

runConn = do
  s <- withSocketsDo (listenOn (PortNumber 1234))
  p <- atomically (newTVar ([]::[ThreadId]))
  t <- forkIO (repeatAccept s p)
  repeatUntilExit stdin stdout putChar ""
  p' <- atomically (readTVar p)
  mapM killThread (t:p')

repeatAccept s p = do
  a <- accept s
  t <- forkFinally (echoHandler a) (exitPool p) -- Error here, forkIO instead compiles fine.. (and I guess actually should work just fine too?)
  atomically $ do
    p' <- readTVar p
    writeTVar p (t:p')
  repeatAccept s p

exitPool :: Pool -> a -> IO ()
exitPool pool = \_ -> do
  tid <- myThreadId
  atomically $ do
    pool' <- readTVar pool
    writeTVar pool $ filter (/=tid) pool'
    return ()

echoHandler :: ConnectionHandler
echoHandler a@(hdl,_,_) = repeatUntilExit hdl hdl echoToHandleAndStdout ""
  where echoToHandleAndStdout x = hPutChar hdl x >> putChar x

repeatUntilExit :: Handle -> Handle -> (Char -> IO ()) -> [Char] -> IO ()
repeatUntilExit hIn hOut f "exit\n" = hPutStrLn hOut "bye\n"
repeatUntilExit hIn hOut f x = hGetChar hIn >>= \c -> f c >> repeatUntilExit hIn hOut f (appendToLastFive c)
  where appendToLastFive a = (reverse . (:)a . take 4 . reverse) x

forkFinally :: Exception e => IO a -> (Either e a -> IO ()) -> IO ThreadId
forkFinally action and_then =
  mask $ \restore ->
    forkIO $ try (restore action) >>= and_then

1 个答案:

答案 0 :(得分:6)

在最新的Control.Concurrent中输入forkFinally的签名:

forkFinally :: IO a -> (Either SomeException a -> IO ()) -> IO ThreadId

在代码中为forkFinally键入签名:

forkFinally :: Exception e => IO a -> (Either e a -> IO ()) -> IO ThreadId

您试图概括异常类型。如果可以从forkFinally的第二个参数推导出异常类型,则这不是问题。但这是forkFinally的第二个参数:

exitPool p :: a' -> IO ()

类型检查器会尝试将Either e a -> IO ()a' -> IO ()统一起来,最终无法推断e是什么。

常规解决方案:指定显式类型。 e.g。

t <- forkFinally (echoHandler a) (exitPool p :: Either SomeException () -> IO ())

更具体的解决方案:将原始类型签名恢复为forkFinally。它只能捕获一组有限的例外似乎没有意义。