我可以确保 Haskell 执行原子 IO 吗? [英] Can I ensure that Haskell performs atomic IO?
问题描述
我在 haskell 中有两个线程来执行 IO.(他们只打印).类似于以下内容:
I have two threads in haskell that perform IO. (They print only). Something like the following:
thread1 :: IO ()
thread1 = putStrLn "One"
thread2 :: IO ()
thread2 = putStrLn "Two"
我目前得到的结果如下:
I am currently getting results like the following:
OnTwoe
OTnweo
如何确保每个线程都原子地完成其 IO?
How can I ensure that each thread completes its IO atomically?
推荐答案
使用同步变量来确保对资源的原子访问.一个简单的方法是使用 MVar:
Use a synchronization variable to ensure atomic access to the resource. A simple way is with an MVar:
main = do
lock <- newMVar ()
forkIO $ ... lock
forkIO $ ... lock
现在,为了不交错进行 IO,每个线程都获取锁:
Now, to do IO without interleaving, each thread takes the lock:
thread1 lock = do
withMVar lock $ \_ -> putStrLn "foo"
thread2 lock = do
withMVar lock $ \_ -> putStrLn "bar"
另一种设计是有一个专门的工作线程来执行所有putStrLns
,然后您发送消息以通过 Chan 打印出来.
An alternate design is to have a dedicated worker thread that does all the putStrLns
, and you send messages to print out over a Chan.
这篇关于我可以确保 Haskell 执行原子 IO 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!