Files
bulma/waitgroup_demo.go
T

32 lines
685 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"
"sync"
"time"
)
var wg4 sync.WaitGroup
// 模拟子任务
func processTask(taskID int) {
defer wg4.Done() // 任务完成后计数器-1
fmt.Printf("任务%d: 开始执行\n", taskID)
// 模拟任务耗时(不同任务耗时不同)
time.Sleep(time.Duration(taskID) * 300 * time.Millisecond)
fmt.Printf("任务%d: 执行完成\n", taskID)
}
func main() {
fmt.Println("主线程: 启动子任务")
// 启动5个并发任务
for i := 1; i <= 5; i++ {
wg4.Add(1) // 计数器+1
go processTask(i)
}
wg4.Wait() // 阻塞至所有任务完成(计数器=0
fmt.Println("主线程: 所有子任务完成,继续执行后续逻辑")
}