0
点赞
收藏
分享

微信扫一扫

Golang 顺序执行协程任务的n种方法之sync.Cond

凌得涂 2022-01-06 阅读 101
package main

import (
 "log"
 "math/rand"
 "sync"
 "time"
)

type A struct {
 C *sync.Cond
 I int
}

func main() {
 c := &A{
  C: sync.NewCond(&sync.Mutex{}),
  I: 1,
 }
 for i := 1000; i > 0; i-- {
  go gog(i, c)
 }
 c.C.L.Lock()
 for c.I != 1001 {
  c.C.Wait()
 }
 c.C.L.Unlock()
}

func gog(index int, c *A) {
 c.C.L.Lock()
 for c.I != index {
  c.C.Wait()
 }
 //模拟任务
 time.Sleep(time.Millisecond * time.Duration(rand.Intn(200)))
 log.Println(index)
 c.I = index + 1
 c.C.L.Unlock()
 c.C.Broadcast()
}
举报

相关推荐

Golang的goroutine协程

0 条评论