package main
import (
"fmt"
"sync"
)
// TaskFinishNotice 定义任务完成通知结构体,可根据自身业务定义
type TaskFinishNotice struct {
TaskName string
TaskResult string
}
func main() {
defer func() {
if err := recover(); err != any(nil) {
fmt.Println("主协程产生panic: ", err)
}
}()
waitGroup := &sync.WaitGroup{}
//任务数量
taskNums := 2
waitGroup.Add(taskNums)
//定义结果集channel
resultChannel := make(chan TaskFinishNotice, taskNums)
go func() {
//捕获一下协程内的panic
defer func() {
if err := recover(); err != any(nil) {
fmt.Println("任务taskOne, 产生panic: ", err)
}
}()
defer waitGroup.Done()
//将任务返回值投递到结果集通道
taskResult := taskOne()
resultChannel <- TaskFinishNotice{TaskName: "taskOne", TaskResult: taskResult}
}()
go func() {
//捕获一下协程内的panic
defer func() {
if err := recover(); err != any(nil) {
fmt.Println("任务taskTwo, 产生panic: ", err)
}
}()
defer waitGroup.Done()
//将任务返回值投递到结果集通道
taskResult := taskTwo()
resultChannel <- TaskFinishNotice{TaskName: "taskTwo", TaskResult: taskResult}
}()
//等待所有协程任务完成并关闭结果集通道
go func() {
//捕获一下协程内的panic
defer func() {
if err := recover(); err != any(nil) {
fmt.Println("等待所有协程任务完成并关闭结果集通道产生panic: ", err)
}
}()
//关闭结果集通道
defer close(resultChannel)
waitGroup.Wait()
}()
//读取结果集
for result := range resultChannel {
fmt.Printf("%+v \n", result)
}
//打印结果:
//{TaskName:taskOne TaskResult:This is taskOne Result.}
//{TaskName:taskTwo TaskResult:This is taskTwo Result.}
}
func taskOne() string {
return "This is taskOne Result."
}
func taskTwo() string {
return "This is taskTwo Result."
}
golang 利用channel收集多协程返回值
于 2022-10-03 22:49:01 首次发布