示例代码:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42package main
import (
"context"
"fmt"
"sync"
"time"
"golang.org/x/sync/semaphore"
)
func doSomething(u string) {
fmt.Println(u)
time.Sleep(2 * time.Second)
}
const (
Limit = 3 // 最大并发执行次数
Weight = 1
)
func main() {
urls := []string{
"http://www.example.com",
"http://www.example.net",
"http://www.example.net/foo",
"http://www.example.net/bar",
"http://www.example.net/baz",
}
s := semaphore.NewWeighted(Limit)
var w sync.WaitGroup
for _, u := range urls {
w.Add(1)
s.Acquire(context.Background(), Weight)
go func(u string) {
doSomething(u)
s.Release(Weight)
w.Done()
}(u)
}
w.Wait()
}
使用信号量实现 goroutine 并发控制
赏
如果觉得文章对您有用,请打赏二两银子~
