我可以确保Haskell执行原子IO吗? [英] Can I ensure that Haskell performs atomic IO?
问题描述
我有两个线程在haskell执行IO。 (仅打印)。类似如下:
thread1 :: IO()
thread1 = putStrLnOne
thread2 :: IO()
thread2 = putStrLnTwo
目前得到的结果如下:
OnTwoe
pre>
OTnweo
如何确保每个线程原子地完成其IO?
解决方案这是一个好问题。使用同步变量确保对资源的原子访问。一个简单的方法是使用MVar:
main = do
lock< - newMVar()
forkIO $ ... lock
forkIO $ ... lock
无交叉,每个线程采用锁:
thread1 lock = do
withMVar lock $ \_ - > putStrLnfoo
thread2 lock = do
withMVar lock $ \_ - > putStrLnbar
另一种设计是有一个专用的工作线程来执行所有的putStrLns,您发送邮件通过Chan打印。
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
How can I ensure that each thread completes its IO atomically?
解决方案This is a good question. 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
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"
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屋!