Dong.Ge

左手代码 右手江湖

golang goroutine

东哥's Avatar 2019-05-10

用锁实现

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
package main

import (
"fmt"
"sync"
)

var counter int = 0

func Count(lock *sync.Mutex) {
lock.Lock()
counter++
fmt.Println("counter =", counter)
lock.Unlock()
}

func main() {

lock := &sync.Mutex{}

for i := 0; i < 10; i++ {
go Count(lock)
}

for {
c := counter
if c >= 10 {
fmt.Println("end")
break
}
}
}

用channel实现

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
package main

import (
"fmt"
)

func Count(ch chan int, i int) {
fmt.Println("Counting:", i)
ch <- 1
}

func main() {

chs := make([]chan int, 10)

for i := 0; i < 10; i++ {
chs[i] = make(chan int, 0)
go Count(chs[i], i)
}

for _, ch := range chs {
<-ch
}
fmt.Println("end")
}

本文最后更新于 天前,文中所描述的信息可能已发生改变