-
-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathtimeouts.hs
63 lines (54 loc) · 1.51 KB
/
timeouts.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
{-# LANGUAGE LambdaCase, NumericUnderscores #-}
import Data.Foldable (asum)
import Control.Concurrent (forkIO, threadDelay)
import Control.Concurrent.STM (atomically, retry)
import Control.Concurrent.STM.TVar
main =
do
result <- atomically (newTVar Nothing)
forkIO $
do
threadDelay 2_000_000
atomically (writeTVar result (Just
"Task A: Completed in two seconds"))
timeout <- atomically (newTVar False)
forkIO $
do
threadDelay 1_000_000
atomically (writeTVar timeout True)
message <- atomically $
asum
[ readTVar result >>=
\case
Nothing -> retry
Just x -> return x
, readTVar timeout >>=
\case
False -> retry
True -> return "Task A: Gave up after one second"
]
putStrLn message
----
result <- atomically (newTVar Nothing)
forkIO $
do
threadDelay (500_000)
atomically (writeTVar result (Just
"Task B: Completed in half a second"))
timeout <- atomically (newTVar False)
forkIO $
do
threadDelay 1_000_000
atomically (writeTVar timeout True)
message <- atomically $
asum
[ readTVar result >>=
\case
Nothing -> retry
Just x -> return x
, readTVar timeout >>=
\case
False -> retry
True -> return "Task B: Gave up after one second"
]
putStrLn message