Is this a bug in multithreading code?
Remi Turk
rturk@science.uva.nl
Wed, 23 Apr 2003 22:21:55 +0200
On Wed, Apr 23, 2003 at 03:51:25PM +0200, Nick Name wrote:
> Hi all, does someone know why this program works
>
> ------------------------
> import Concurrent
>
> loopM = sequence_ . repeat
>
> main = do
> v <- newMVar 0
> forkIO (loopM (modifyMVar_ v (return . (1+))))
> -- forkIO (loopM (modifyMVar_ v (return . (1+))))
> loopM (readMVar v >>= print)
> -------------------------
>
> but uncommenting the commented line makes the program fail with "stack
> overflow" ?
>
> Thanks for help
>
> Vincenzo
It definitely seems a bug to me. Though I'm not sure if it's in your
code or in Concurrent ;)
However, the following code _does_ work, which makes me suspect
it has something to do with the locking done inside of an MVar.
import Control.Concurrent
loopM = sequence_ . repeat
main = do
v <- newMVar 0
forkIO $ loopM $ do
modifyMVar_ v $ return . (1+)
forkIO $ loopM $ do
modifyMVar_ v $ return . (1+)
loopM $ do
readMVar v >>= print
--withMVar v print
Swapping the last 2 lines (that is, their comments) makes it crash again.
And I guess this actually _is_ the code you should use:
withMVar is a "safe wrapper for operating on the contents of an MVar",
which is exactly what you're doing.
Does anyone else know what exactly is going on?
Happy hacking,
Remi
--
Nobody can be exactly like me. Even I have trouble doing it.