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
|
{- | A Go-like EDSL to make working with concurrent in-process code a bit
easier to read.
This module is expected to be imported qualified as `Go`.
$example
-}
{-# LANGUAGE NoImplicitPrelude #-}
module Com.Simatime.Go
(
-- * Running and forking
Go
, run
, fork
-- * Channels
, Channel
, chan
, read
, write
)
where
import Control.Concurrent ( forkIO
, ThreadId
)
import Control.Concurrent.STM.TChan ( newTChan
, readTChan
, writeTChan
, TChan
)
import GHC.Conc ( STM
, atomically
)
import Protolude ( IO()
, MonadIO(liftIO)
, flip
, (.)
)
type Go = STM
type Channel = TChan
-- | Runs a Go command in IO.
run :: Go a -> IO a
run = atomically
-- | Starts a background process.
fork :: IO () -> IO ThreadId
fork = forkIO
-- | Make a new channel.
chan :: Go (Channel a)
chan = newTChan
-- | Take from a channel. Blocks until a value is received.
read :: Channel a -> Go a
read = readTChan
-- | Write to a channel.
write :: Channel a -> a -> Go ()
write = writeTChan
{- $example
A simple example from ghci:
>>> import qualified Com.Simatime.Go as Go
>>> c <- Go.run Go.chan :: IO (Go.Channel Text)
>>> Go.run $ Go.write c "test"
>>> Go.run $ Go.read c
"test"
-}
|