add: waitgroup的用法
This commit is contained in:
parent
8cfb6c3d06
commit
63f6788a12
59
waitgroup/example1/main.go
Normal file
59
waitgroup/example1/main.go
Normal file
@ -0,0 +1,59 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
|
||||||
|
// test1 不传递wg,用匿名函数运行
|
||||||
|
func test1() {
|
||||||
|
wg.Add(2)
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
Info("task1")
|
||||||
|
}()
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
Info("task2")
|
||||||
|
}()
|
||||||
|
wg.Wait()
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
//test2 for循环并发
|
||||||
|
func test2() {
|
||||||
|
for i := 0; i <= 10; i++ {
|
||||||
|
wg.Add(1)
|
||||||
|
go func(a int) {
|
||||||
|
defer wg.Done()
|
||||||
|
Info("test" + strconv.Itoa(a+1))
|
||||||
|
}(i)
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
}
|
||||||
|
//test3 并发限速
|
||||||
|
func test3() {
|
||||||
|
limit := make(chan struct{}, 2)
|
||||||
|
for i := 0; i < 100; i++ {
|
||||||
|
wg.Add(1)
|
||||||
|
limit <- struct{}{}
|
||||||
|
go func(a int) {
|
||||||
|
defer func() {
|
||||||
|
wg.Done()
|
||||||
|
<-limit
|
||||||
|
}()
|
||||||
|
Info("test" + strconv.Itoa(i+1))
|
||||||
|
}(i)
|
||||||
|
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
}
|
||||||
|
|
||||||
|
func Info(name string) {
|
||||||
|
time.Sleep(time.Second)
|
||||||
|
fmt.Printf("this is a %v task...->%v\n", name, time.Now())
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user