forked from simonmar/parconc-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chan2.hs
66 lines (58 loc) · 1.42 KB
/
chan2.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import Control.Concurrent hiding (Chan, newChan, readChan, writeChan, dupChan)
-- <<Stream
type Stream a = MVar (Item a)
data Item a = Item a (Stream a)
-- >>
-- <<Chan
data Chan a
= Chan (MVar (Stream a))
(MVar (Stream a))
-- >>
-- <<newChan
newChan :: IO (Chan a)
newChan = do
hole <- newEmptyMVar
readVar <- newMVar hole
writeVar <- newMVar hole
return (Chan readVar writeVar)
-- >>
-- <<writeChan
writeChan :: Chan a -> a -> IO ()
writeChan (Chan _ writeVar) val = do
newHole <- newEmptyMVar
oldHole <- takeMVar writeVar
putMVar oldHole (Item val newHole)
putMVar writeVar newHole
-- >>
-- <<readChan
readChan :: Chan a -> IO a
readChan (Chan readVar _) = do
stream <- takeMVar readVar
Item val tail <- readMVar stream -- <1>
putMVar readVar tail
return val
-- >>
-- <<dupChan
dupChan :: Chan a -> IO (Chan a)
dupChan (Chan _ writeVar) = do
hole <- takeMVar writeVar
putMVar writeVar hole
newReadVar <- newMVar hole
return (Chan newReadVar writeVar)
-- >>
-- <<unGetChan
unGetChan :: Chan a -> a -> IO ()
unGetChan (Chan readVar _) val = do
newReadEnd <- newEmptyMVar -- <1>
readEnd <- takeMVar readVar -- <2>
putMVar newReadEnd (Item val readEnd) -- <3>
putMVar readVar newReadEnd -- <4>
-- >>
main = do
c <- newChan
writeChan c 'a'
readChan c >>= print
c2 <- dupChan c
writeChan c 'b'
readChan c >>= print
readChan c2 >>= print