我目前正在运行未知数量的工作人员,产生未知数量的结果,如果新结果比以前的结果更好,这些结果将被放入 MVar 并打印。这发生在printMaxResult
下面显示的函数中。
main = do
startTime <- getCurrentTime
-- Read problem
numbers <- parseList
target <- parseTargetNumber
-- Create mvar to communicate
mvar <- newEmptyMVar
-- Start solving the actual problem
-- The solve methods will write their results
-- into the given mvar
forkIO $ SimpleAdd.solve (Problem target numbers) mvar
forkIO $ IncrementDecrement.solve (Problem target numbers) mvar incOps decOps
-- Read the first result and use it to go into the "main loop"
expr <- takeMVar mvar
debugPrintExpr expr startTime
printMaxResult mvar expr startTime
return ()
-- Extracts a new result from the given mvar and compares
-- it with the previous result. If the new result has a
-- better score it remembers it and prints it.
printMaxResult :: MVar Expr -> Expr -> UTCTime -> IO ()
printMaxResult mvar expr startTime = do
newExpr <- takeMVar mvar
if score newExpr > score expr
then do
debugPrintExpr newExpr startTime
printMaxResult mvar newExpr startTime
else
printMaxResult mvar expr startTime
问题是,一旦所有线程完成,程序就会崩溃,但出现以下异常:main: thread blocked indefinitely in an MVar operation
. 当然,这条消息是正确的:MVar 不可能随时接收到一些新的输入。
但是我该如何优雅地处理这种情况呢?我可以处理该异常并执行“exit(0)”之类的操作。我试图了解异常处理在 Haskell 中是如何工作的,但我无法真正理解它。