forked from simonmar/parconc-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.hs
56 lines (48 loc) · 979 Bytes
/
logger.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
import Control.Concurrent
import Control.Monad
-- -----------------------------------------------------------------------------
-- <<Logger
data Logger = Logger (MVar LogCommand)
data LogCommand = Message String | Stop (MVar ())
-- >>
-- <<initLogger
initLogger :: IO Logger
initLogger = do
m <- newEmptyMVar
let l = Logger m
forkIO (logger l)
return l
-- >>
-- <<logger
logger :: Logger -> IO ()
logger (Logger m) = loop
where
loop = do
cmd <- takeMVar m
case cmd of
Message msg -> do
putStrLn msg
loop
Stop s -> do
putStrLn "logger: stop"
putMVar s ()
-- >>
-- <<logMessage
logMessage :: Logger -> String -> IO ()
logMessage (Logger m) s = putMVar m (Message s)
-- >>
-- <<logStop
logStop :: Logger -> IO ()
logStop (Logger m) = do
s <- newEmptyMVar
putMVar m (Stop s)
takeMVar s
-- >>
-- <<main
main :: IO ()
main = do
l <- initLogger
logMessage l "hello"
logMessage l "bye"
logStop l
-- >>