English 中文(简体)
如何从动态渠道清单中读取,而不必间断
原标题:How to read from dynamic list of channels without spawning a goroutine per channel

我知道,在 go兰, go虫非常便宜,但出于好奇,我们可以说:


    go func() {
        for {
            select {
            case <-stop:
                return // Stop goroutine when stop signal is received
            default:
                // Read from each channel
                for _, ch := range channels {
                    select {
                    case val := <-ch:
                        fmt.Printf("Received from channel: %d
", val)
                    default:
                        // If channel is empty, continue to the next channel
                    }
                }
                time.Sleep(time.Millisecond * 100) // Add a short delay to prevent busy-waiting
            }
        }
    }()

综上所述,我们有一个动态的清单(渠道),但是,它会阻碍每一个机制。 我所期待的基本上是一份“动态选择”声明,它有大量的案件陈述(在汇编时间没有)。

也许没有必要避免使一条不同的通道变成一条不同的通道,但此时,如果可能的话,我会感到奇怪。

问题回答

可使用<代码>reflect.Select:

chn1:=reflect.ValueOf(channel1)
...
cases:=[]reflect.SelectCase{
  {
     Dir: reflect.SelectRecv,
     Chan: chn1,
  },
  {
     Dir: reflect.SelectRecv,
     Chan: chn2,
  }
}

...
chosen, value, ok:=reflect.Select(cases)




相关问题
minimum work size of a goroutine [closed]

Does anyone know approximately what the minimum work size is needed in order for a goroutine to be beneficial (assuming that there are free cores for the work to be offloaded to)?

How do you get the terminal size in Go?

How do I get the terminal size in Go. In C it would look like this: struct ttysize ts; ioctl(0, TIOCGWINSZ, &ts); But how to i access TIOCGWINSZ in Go

What do you use to write Go [closed]

I know its a bit too early, but I ve been trying out Go (Google s Programming Language) and its kindof annoying to write code in gedit. So, my question: What do you use to experiment with Go?

Shared memory vs. Go channel communication

One of Go s slogans is Do not communicate by sharing memory; instead, share memory by communicating. I am wondering whether Go allows two different Go-compiled binaries running on the same machine to ...

Embedding instead of inheritance in Go

What is your opinion of this design decision? What advantages does it have and what disadvantages? Links: Embedding description

热门标签