-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconcurrency.go
More file actions
80 lines (68 loc) · 1.47 KB
/
concurrency.go
File metadata and controls
80 lines (68 loc) · 1.47 KB
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
package main
import (
"fmt"
"log"
"time"
)
func concurrecncyExample() {
apporder := make(chan order, 3)
inShopOrder := make(chan order, 3)
queue := make(chan order, 3)
go func() {
for i := 0; i < 6; i++ {
apporder <- order(100 + i)
time.Sleep(10 * time.Second)
}
close(apporder)
}()
go func() {
for i := 0; i < 4; i++ {
inShopOrder <- order(200 + i)
time.Sleep(15 * time.Second)
}
close(inShopOrder)
}()
go partier(apporder, inShopOrder, queue)
for o := range queue {
log.Printf("Served %s\n", o)
}
log.Println("Done!")
}
func partier(
appOrders <-chan order,
inShopOrders <-chan order,
queue chan<- order,
) {
shouldClose := false
closeTimeCh := time.After(1 * time.Minute)
for !shouldClose {
select {
case ord, ok := <-appOrders:
if ok {
log.Printf("There is %s coming from appOrders channel\n", ord)
queue <- ord
}
case ord, ok := <-inShopOrders:
if ok {
log.Printf("There is %s coming from inShopOrders channel\n", ord)
queue <- ord
}
case now := <-closeTimeCh:
log.Printf("It is %v now, the shop is closing\n", now)
shouldClose = true
default:
log.Println("There is no order on both channels, I will go cleaning instead")
doCleaning()
}
}
close(queue)
log.Println("Shop is closed, I’m going home now. Bye!")
}
func doCleaning() {
time.Sleep(5 * time.Second)
log.Println("Partier: Cleaning done")
}
type order int
func (o order) String() string {
return fmt.Sprintf("order-%02d", o)
}