1. 使用场景:
    通常用于控制处理切片或消息队列的并发量

  2. 代码:

     package main
    
     import (
         "context"
         "fmt"
         "golang.org/x/sync/semaphore"
         "time"
     )
    
     func main() {
         arr := []int{1, 2, 3, 4, 5}
         s := semaphore.NewWeighted(2) // 设置并发量为2
         for _, item := range arr {
             go func(i int) {
                 s.Acquire(context.Background(), 1) // 设置权重为1
                 fmt.Println(i)
                 time.Sleep(time.Second)
                 s.Release(1)
             }(item)
         }
         time.Sleep(5 * time.Second)
         fmt.Println("All Done")
     }
文档更新时间: 2024-04-20 10:57   作者:lee