golang控制协程数量

人活一生,值得爱的东西很多,不要因为一个不满意,就灰心

DEMO1

1
2
3
4
for _,v := range Uins{
// Query the corresponding user information for each UIN
go getUserInfo(v)
}

DEMO2

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
func main(a){
// Create an empty structure channel with size 512
channel := make(chan struct{},512)
/ / create a sync. WaitGroup
var wg sync.WaitGroup
// Wg is the length of Uins
wg.Add(len(Uins))
for_,v:= range Uins{
channel <- struct{} {}// Pass WG as a parameter to the coroutine
go getUserInfo(v,channel,&wg)
}
// block until wg is 0
wg.Wait()
return
}


func getUserInfo(v int,channel chan struct{},wg *sync.WaitGroup){
defer func(a) {
// Wargaming is reduced by 1 before return
wg.Done()
<-channel
}()
/**
业务逻辑
**/
}

DEMO3

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
package main

import (
"fmt"
"sync"
)

func main() {
count := 10
sum := 100
wg := sync.WaitGroup{}

c := make(chan struct{}, count)
defer close(c)

for i:=0; i<sum;i++{
wg.Add(1)
go func(j int) {
defer wg.Done()
c <- struct{}{}
fmt.Println(j)
}(i)
<- c
}
wg.Wait()
}

DEMO4

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
42
43
44
45
46
47
package main

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

func main() {

maxnum := make(chan struct{}, 5)
setPool(maxnum)

wg := sync.WaitGroup{}
wg.Add(5)

go func() {
for {
wg.Wait()
fmt.Println("=======发放5个任务=========")
setPool(maxnum)
wg.Add(5)
}
}()


for {
<-maxnum
go func() {
defer wg.Done()
myJob()
}()
}

}

func setPool(ch chan struct{}) {
for i:=0; i<5; i++ {
ch <- struct{}{}
}
}

func myJob() {
time.Sleep(time.Second * 3)
fmt.Println(rand.Intn(100))
}