golanglearn/waitgroup/example1/main.go
2022-01-19 12:08:37 +08:00

60 lines
823 B
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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())
}