-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEventLoop.hs
97 lines (73 loc) · 2.45 KB
/
EventLoop.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
{-# LANGUAGE RecordWildCards, BangPatterns #-}
import Control.Monad
import Control.Exception
import Control.Concurrent
import Control.Concurrent.QSem
import Control.Concurrent.Async
import Control.Concurrent.STM
import Control.Concurrent.STM.TChan
import System.Random
data Any
= AnyNull
| AnyInt Int
| AnyDouble Double
| AnyChar Char
| AnyString String
| AnyList [Any]
deriving Show
data Event
= Close
| Event
{ func :: IO Any
, callback :: Any -> IO Any
}
main :: IO ()
main = do
taskQueue <- atomically $ newTChan
backgroundChannel <- atomically $ newTChan
let poolSize = 2
concurrently_
(mainThread poolSize taskQueue backgroundChannel)
(background poolSize backgroundChannel taskQueue)
mainThread :: Int -> TChan (Maybe Any) -> TChan Event -> IO ()
mainThread n receiver sender =
concurrently_
(send `finally` replicateM_ n close)
(get n)
where
close = atomically . writeTChan sender $ Close
send = do
putStrLn "Try add 2 and 2"
event (pure $ AnyInt $ 2 + 2) pure
putStrLn "Try multiply 3 and 4"
event (pure $ AnyInt $ 3 * 4) pure
putStrLn "Try subtract 5 and 3"
event (pure $ AnyInt $ 5 - 3) pure
putStrLn "Try divide 10 and 2 then subtract 2"
event (pure $ AnyInt $ 10 `div` 2) $ \(AnyInt x) -> do
pure $ AnyInt (x - 2)
event f c = atomically . writeTChan sender $ Event f c
get 0 = pure ()
get n = do
result <- atomically $ readTChan receiver
case result of
Nothing ->
get (n-1)
Just x -> do
print x
get n
background :: Int -> TChan Event -> TChan (Maybe Any) -> IO ()
background n receiver sender = do
foldr concurrently_ (pure ()) $ replicate n loop
where
loop = do
task <- atomically $ readTChan receiver
case task of
Close ->
atomically $ writeTChan sender Nothing
Event{..} -> do
!result <- func >>= callback
r <- randomRIO (1,4) :: IO Int
threadDelay $ r * 1000000 -- ^ To simulate computational cost
atomically $ writeTChan sender (Just result)
loop