multithreading - Sharing a mvar between threads -
i'm trying make program print arrows until user press enter (see code bellow).
the problem when press enter, see "stop" string in console, doesn't change value of m in outputarrows function.
how can share state?
import control.concurrent import control.concurrent.async import control.monad waitforinput m = getline putstrln "stop" putmvar m true outputarrows m = stop <- readmvar m unless stop $ threaddelay 1000000 putstr ">" outputarrows m main = m <- newmvar false th1 <- async (waitforinput m) th2 <- async (outputarrows m) wait th1 wait th2
your putmvar
doesn't put new value in mvar
blocks indefinitely. mvars boxes can hold single value. if want replace value, need take out old value first.
if don't need blocking behavior of mvar, should use regular ioref
or possibly tvar
if need ensure more complex operations run atomically.
Comments
Post a Comment