Golang 两个携程交替输出1-10

Golang 两个携程交替输出1-10


百度搜索了一些相关话题,感觉不是很好所以自己写了一个。技术栈waitgroup主进程等待,context携程退出,chan通信。理论上有这三点基本都可以,不过感觉个人实现的还不是很完美,望各位指正~

func Test4(t *testing.T) {
   s := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
   wg := sync.WaitGroup{}
   wg.Add(1) //注意这里为什么是1不是2:虽然是两个携程同时在运行,但是wg.Wait()只需要知道一个goroutine执行完毕,即不等待。后续通过context来终止携程运行。
   c1 := make(chan int, 1)
   defer close(c1)
   c2 := make(chan int, 1)
   defer close(c2)

   c1 <- 0
   ctx, cancel := context.WithCancel(context.Background())
   go func(ctx context.Context, c1, c2 chan int) {
      for {
         select {
         case index := <-c1:
            if index%2 == 0 {
               fmt.Println("1--", index)
               fmt.Println("=====================goroutine1 print :", s[index])
               if index+1 >= len(s) {
                  wg.Done()
               } else {
                  c2 <- index + 1
               }
            }
         case <-ctx.Done():
            fmt.Println("----------------------------goroutine2 exit ...")
            return            }
      }
   }(ctx, c1, c2)

   go func(ctx context.Context, c1, c2 chan int) {
      for {
         select {
         case index := <-c2:
            if index%2 == 1 {
               fmt.Println("2--", index)
               fmt.Println("=====================goroutine1 print :", s[index])
               if index+1 >= len(s) {
                  wg.Done()
               } else {
                  c1 <- findex + 1
               }
            }
         case <-ctx.Done():
            fmt.Println("----------------------------goroutine2 exit ...")
            return
         }
      }
   }(ctx, c1, c2)

   wg.Wait()
   cancel()
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值