我正在编写一个函数,我使用forM_
处理列表,并将结果附加到TVar
列表:
import Control.Concurrent.STM
import Control.Concurrent.STM.TVar
import Control.Concurrent (forkIO)
import Control.Monad (forM_)
insert :: a -> [a] -> [a]
insert = (:) -- stub
my_func_c :: (a -> a) -> [a] -> IO [a]
my_func_c my_function arr = do
res_var <- atomically $ newTVar ([]::[a])
forkIO $ forM_ arr $ \x -> atomically $ do
let y = id $! my_function x
modifyTVar res_var (insert y)
atomically $ readTVar res_var
如果我用-threaded
编译它,结果总是为空的。怎么可能等待线程完成?我无法使用MVar
或Async
。我必须使用TVar
或其他基于TVar
答案 0 :(得分:3)
惯用解决方案是使用TMVar
s:
my_func_c :: (a -> a) -> [a] -> IO [a]
my_func_c my_function arr = do
res_var <- atomically $ newTVar []
finished <- atomically $ newEmptyTMVar
forkIO $ do
forM_ arr $ \x -> atomically $ do
let y = id $! my_function x
modifyTVar res_var (insert y)
atomically $ putTMVar finished ()
atomically $ takeTMVar finished >> readTVar res_var
但如果您真的只允许使用TVar
,则可以使用TMVar ()
模拟TVar Bool
:
my_func_c :: (a -> a) -> [a] -> IO [a]
my_func_c my_function arr = do
res_var <- atomically $ newTVar []
finished <- atomically $ newTVar False
forkIO $ do
forM_ arr $ \x -> atomically $ do
let y = id $! my_function x
modifyTVar res_var (insert y)
atomically $ writeTVar finished True
atomically $ waitTVar finished >> readTVar res_var
waitTVar :: TVar Bool -> STM ()
waitTVar tv = do
finished <- readTVar tv
unless finished retry
引导TMVar a
is just a TVar (Maybe a)
(TMVar ()
〜TVar (Maybe ())
〜TVar Bool
)与takeTMVar
doing a readTVar
and a retry
,所以上述两种解决方案在操作上完全等效。< / p>