golang多个goroutinue顺序打印数字

一. 10个goroutinue顺序打印0-9

常规的做法是用10个channel来挨个控制,其实可以用原子包实现,相当于加锁

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
func printInOrder() {
wg := sync.WaitGroup{}
var curr int32
for i := int32(0); i < 10; i++ {
wg.Add(1)
go func(num int32) {
defer wg.Done()
for {
if n := atomic.LoadInt32(&curr); n == num {
fmt.Println(num)
atomic.AddInt32(&curr, 1)
break
}
time.Sleep(time.Nanosecond)
}
}(i)
}

wg.Wait()
}

二. 两个goroutinue分别打印奇偶数

同上,还是用原子包

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
func printMix() {
wg := sync.WaitGroup{}
var curr int32
wg.Add(2)
go func() {
defer wg.Done()
for curr < 10 {
if n := atomic.LoadInt32(&curr); n%2 == 1 {
fmt.Println("A:", n)
atomic.AddInt32(&curr, 1)
} else {
time.Sleep(time.Nanosecond)
}
}
}()
go func() {
defer wg.Done()
for curr < 10 {
if n := atomic.LoadInt32(&curr); n%2 == 0 {
fmt.Println("B:", n)
atomic.AddInt32(&curr, 1)
} else {
time.Sleep(time.Nanosecond)
}
}
}()

wg.Wait()
}

请我喝咖啡
liaol WeChat Pay

微信打赏