-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
74 lines (63 loc) · 1.16 KB
/
main.go
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
package main
import (
"context"
"errors"
"fmt"
"log"
"os"
"os/signal"
"sync"
"time"
)
var (
totalInventory int
inventorylock sync.Mutex
wg sync.WaitGroup
)
func AddToInventory(ctx context.Context, inventory int) {
select {
case <-ctx.Done():
return
default:
}
go func() {
wg.Add(1)
if err := process(inventory); err != nil {
log.Print("Inventory is not valid")
}
wg.Done()
}()
}
func process(inventory int) error {
if inventory < 0 {
return errors.New("inventory could not be negative")
}
// It takes two seconds to process the request.
time.Sleep(time.Second * 2)
log.Print("inventory proceed successfully")
inventorylock.Lock()
totalInventory += inventory
inventorylock.Unlock()
return nil
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
addInventories(ctx)
ch := make(chan os.Signal, 1)
signal.Notify(ch, os.Interrupt)
go func() {
for range ch {
cancel()
wg.Wait()
fmt.Println("canceled:", totalInventory)
os.Exit(0)
}
}()
wg.Wait()
fmt.Println("finished:", totalInventory)
}
func addInventories(ctx context.Context) {
for i := 0; i < 10; i++ {
AddToInventory(ctx, i)
}
}