golang 并发处理

背景

需要并发的处理的任务

查阅

使用 waitgroup chan

代码实现

package main

import (
   "fmt"
   "sync"
)

func main() {

   var l []int
   receive := func(w chan int, wg *sync.WaitGroup) {
      for data := range w {
         l = append(l, data)
         wg.Done()
      }
       close(w)
   }

   send := func(index int, w chan int) {
      w <- index
   }

   wg := new(sync.WaitGroup)
   ws := make(chan int)
   go receive(ws, wg)
   for i := 0; i < 100; i++ {
      wg.Add(1)
      go send(i, ws)
   }
   wg.Wait()
   fmt.Print(len(l), "\t")

}

posted @ 2022-04-13 13:52  vx_guanchaoguo0  阅读(57)  评论(0编辑  收藏  举报