在线程之间共享mvar

Bru*_*uno 3 concurrency multithreading haskell

我正在尝试制作一个打印箭头的程序,直到用户按下回车键(参见下面的代码).

问题是,当我按回车键时,我在控制台中看到"停止"字符串,但它不会更改outputArrows函数中的m值.

我该如何分享州?

import Control.Concurrent
import Control.Concurrent.Async
import Control.Monad

waitForInput m = do
    getLine
    putStrLn "stop"
    putMVar m True

outputArrows m = do
    stop <- readMVar m
    unless stop $ do
        threadDelay 1000000
        putStr ">"
        outputArrows m

main = do
    m <- newMVar False
    th1 <- async (waitForInput m)
    th2 <- async (outputArrows m)
    wait th1
    wait th2
Run Code Online (Sandbox Code Playgroud)

sha*_*ang 7

putMVar实际上并没有在其中添加新值MVar但是无限期地阻塞.MVar就像只能容纳一个值的盒子.如果要替换该值,则需要先取出旧值.

如果你不需要MVar的阻塞行为,你应该只使用常规IORef或者可能TVar需要确保更复杂的操作以原子方式运行.