-
Notifications
You must be signed in to change notification settings - Fork 103
/
chan.hs
52 lines (45 loc) · 1.07 KB
/
chan.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
import Control.Concurrent hiding (Chan, newChan, readChan, writeChan)
-- <<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 -- <1>
Item val tail <- takeMVar stream -- <2>
putMVar readVar tail -- <3>
return val
-- >>
-- <<dupChan
dupChan :: Chan a -> IO (Chan a)
dupChan (Chan _ writeVar) = do
hole <- readMVar writeVar
newReadVar <- newMVar hole
return (Chan newReadVar writeVar)
-- >>
main = do
c <- newChan
writeChan c 'a'
readChan c >>= print