登录
首页 >  Golang >  Go问答

带通信通道的 WaitGroup

来源:stackoverflow

时间:2024-03-11 09:06:25 310浏览 收藏

从现在开始,努力学习吧!本文《带通信通道的 WaitGroup》主要讲解了等等相关知识点,我会在golang学习网中持续更新相关的系列文章,欢迎大家关注并积极留言建议。下面就先一起来看一下本篇正文内容吧,希望能帮到你!

问题内容

我一直在研究这个并想出了:

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 的缓冲通道可以工作,而无缓冲通道则不能?
  2. 默认大小不是无缓冲的 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
}

func (x *TaskGroup) Wait() {
    for _, function := range x.Functions{
        x.Group.Add(1)
        go func(x *TaskGroup, f Function){
            defer x.Group.Done()
            f.Function(f.Args)
        }(x, function)
    }
    x.Group.Wait()
}

解决方案


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

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

以上就是《带通信通道的 WaitGroup》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>