Golang多个goroutine顺序输出自然数序列
程序员文章站
2022-03-04 18:53:10
...
package main
import (
"sync/atomic"
"time"
"fmt"
)
func main() {
var number uint32 = 10
//count相当于一个接力棒
var count uint32
trigger := func(i uint32, fn func()) {
//自旋锁
for {
if n := atomic.LoadUint32(&count); n == i {
fn()
//一定要在执行完函数后才原子加1
atomic.AddUint32(&count, 1)
break
}
time.Sleep( 1 * time.Millisecond)
}
}
for i := uint32(0); i < number; i++ {
go func(i uint32) {
fn := func() {
fmt.Println(i)
}
trigger(i, fn)
}(i)
}
trigger(number, func(){})
//会按照自然数顺序打印(一定是这样)
}
上一篇: go字符串
下一篇: go 随聊-defer延迟调用