-
Notifications
You must be signed in to change notification settings - Fork 0
/
15.Select.go
70 lines (59 loc) · 1.59 KB
/
15.Select.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
package main
import (
"fmt"
"sync"
"time"
)
func shoppingAndBuyAndRecord(name string, money int, waitGroup *sync.WaitGroup) {
fmt.Println(name, "在购物\n")
time.Sleep(1 * time.Second)
fmt.Println(name, "购物结束\n")
moneyChannel_1 <- money
nameChannel_1 <- name
waitGroup.Done()
}
// 声明并初始化为一个 长度为0的channel
// channel是一个上了锁的实例
var moneyChannel_1 = make(chan int)
var nameChannel_1 = make(chan string)
var doneChannel = make(chan struct{})
// 注:主线程结束,协程就会结束,所以必须要让主线程等待所有协程完成
func main() {
startTime := time.Now()
var waitGroup sync.WaitGroup
fmt.Println("-------所有人购物开始--------")
waitGroup.Add(2)
go shoppingAndBuyAndRecord("xie", 4, &waitGroup)
go shoppingAndBuyAndRecord("yang", 1, &waitGroup)
go func() {
defer close(moneyChannel_1)
defer close(nameChannel_1)
defer close(doneChannel)
waitGroup.Wait()
}()
var moneyList []int
var nameList []string
var event = func() {
for {
select {
case money := <-moneyChannel_1:
moneyList = append(moneyList, money)
println("接到数据money")
case name := <-nameChannel_1:
nameList = append(nameList, name)
println("接到数据name")
case <-doneChannel:
println("--------doneChannel-------")
return
default:
println("未接到数据")
}
}
}
event()
fmt.Println("-------所有人购物结束--------")
duringTime := time.Since(startTime)
fmt.Println("耗时: ", duringTime)
fmt.Println("总共花了钱: ", moneyList)
fmt.Println("购物的人有", nameList)
}