func TestRoutine() {
RoutineCount := 3
var ch = make(chan int)
arr := []int{15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25}
lock := sync.Mutex{}
index := 0
getOne := func() int {
lock.Lock()
defer lock.Unlock()
if index >= len(arr) {
return 0
}
item := arr[index]
index++
return item
}
doOne := func() {
for {
item := getOne()
if item == 0 {
break
}
fmt.Printf("doOne item=%d\n", item)
}
ch <- 1
}
//
for i := 0; i < RoutineCount; i++ {
go doOne()
}
for i := 0; i < RoutineCount; i++ {
<-ch
}
}
golang 多线程
最新推荐文章于 2023-10-20 11:05:20 发布