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

在使用通道的循环内触发通道

在使用通道的循环内触发通道

Go
跃然一笑 2022-11-23 16:06:48
如何在消耗相同通道的循环内装配通道。下面是一个不起作用的示例代码。这是如何实现的?https://go.dev/play/p/o5ZhNfw4IFupackage mainimport (    "context"    "fmt"    "time")func main() {    ch1 := make(chan struct{})    ch2 := make(chan struct{})    defer close(ch1)    defer close(ch2)    ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)    defer cancel()    go func() {        time.Sleep(time.Second * 1)        ch1 <- struct{}{}    }()loop:    for {        select {        case <-ctx.Done():            fmt.Println("timeout")            break loop        case <-ch1:            fmt.Println("ch1")            ch2 <- struct{}{} // This here does not work!        case <-ch2:            fmt.Println("ch2")        }    }}去
查看完整描述

1 回答

?
泛舟湖上清波郎朗

TA贡献1818条经验 获得超3个赞

1.发送数据到goroutine里面的ch2

package main


import (

    "context"

    "fmt"

    "time"

)


func main() {

    ch1 := make(chan struct{})

    ch2 := make(chan struct{})

    defer close(ch1)

    defer close(ch2)


    ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)

    defer cancel()


    go func() {

        time.Sleep(time.Second * 1)

        ch1 <- struct{}{}

    }()


loop:

    for {

        select {

        case <-ctx.Done():

            fmt.Println("timeout")

            break loop

        case <-ch1:

            fmt.Println("ch1")

            go func() {

                ch2 <- struct{}{}

            }()

        case <-ch2:

            fmt.Println("ch2")

        }

    }


}


或者


2. 使 ch2 缓冲

package main


import (

    "context"

    "fmt"

    "time"

)


func main() {

    ch1 := make(chan struct{})

    ch2 := make(chan struct{}, 1)

    defer close(ch1)

    defer close(ch2)


    ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)

    defer cancel()


    go func() {

        time.Sleep(time.Second * 1)

        ch1 <- struct{}{}

    }()


loop:

    for {

        select {

        case <-ctx.Done():

            fmt.Println("timeout")

            break loop

        case <-ch1:

            fmt.Println("ch1")

            ch2 <- struct{}{}

        case <-ch2:

            fmt.Println("ch2")

        }

    }


}


查看完整回答
反对 回复 2022-11-23
  • 1 回答
  • 0 关注
  • 75 浏览
慕课专栏
更多

添加回答

举报

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