为了账号安全,请及时绑定邮箱和手机立即绑定

带通道的 WaitGroup

带通道的 WaitGroup

Go
LEATH 2023-08-07 14:28:07
我一直在研究这个并想出了:type Function struct{    Function func(*TaskGroup, []interface{})    Args []interface{}}type TaskGroup struct{    Group sync.WaitGroup    Functions []Function}func (x *TaskGroup) Start() {    for _, Function := range x.Functions{        x.Group.Add(1)        go Function.Function(x, Function.Args)    }    x.Group.Wait()}为了更轻松地使用多个功能,我必须等待。以下测试将起作用,我不明白为什么:func auxC(x *TaskGroup, args []interface{}){    defer x.Group.Done()    messageOut := args[0].(chan string)    messageOut <- "TestC"}func auxD(x *TaskGroup, args []interface{}){    defer x.Group.Done()    messageOut := args[0].(chan string)    messageOut <- "TestD"}func TestTaskGroupBaseB(t *testing.T) {    messageC := make(chan string, 1)    messageD := make(chan string, 1)    tg := TaskGroup{        Functions: []Function{            {auxC, []interface{}{messageC}},            {auxD, []interface{}{messageD}},        },    }    tg.Start()    fmt.Println(<- messageC)    fmt.Println(<- messageD)    time.Sleep(100 * time.Millisecond)}我首先尝试使用像这样的无缓冲通道:messageC := make(chan string)messageD := make(chan string)但它不起作用,它只是永远卡住而不做任何事情,所以我有几个问题:为什么大小为 1 的缓冲通道可以工作,而无缓冲通道则不能?默认大小不是无缓冲1吗?重构代码,见注释:主要/测试:func auxC(args []interface{}){    messageOut := args[0].(chan string)    messageOut <- "TestC"}func auxD(args []interface{}){    messageOut := args[0].(chan string)    messageOut <- "TestD"}func TestTaskGroupBaseB(t *testing.T) {    messageC := make(chan string,1)    messageD := make(chan string,1)    tg := TaskGroup{        Functions: []Function{            {auxC, []interface{}{messageC}},            {auxD, []interface{}{messageD}},        },    }    tg.Wait()    fmt.Println(<- messageC)    fmt.Println(<- messageD)    time.Sleep(100 * time.Millisecond)}任务组:type Function struct{    Function func([]interface{})    Args []interface{}}type TaskGroup struct{    Group sync.WaitGroup    Functions []Function
查看完整描述

1 回答

?
Cats萌萌

TA贡献1805条经验 获得超9个赞

使用缓冲区大小为 1 的通道,首先写入缓冲区数据,然后 goroutine 结束,您可以在主 goroutine 中读取缓冲数据。

当通道大小为零时,对通道的写入会阻塞,直到另一个 goroutine 从中读取。所以你的两个 goroutine 都在等待写入通道。如果在通道读入 main 之后移动 Wait() 调用,它应该可以工作。


查看完整回答
反对 回复 2023-08-07
  • 1 回答
  • 0 关注
  • 74 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信