go - 检查 channel 的值

标签 go generator goroutine

我有两个只读 channel <-chan Event用作发电机。

type Event struct{
    time int
}

我可以将它们的值解读为:

for {
    select {
    case <-chan1:
        // do something
    case <-chan2:
        //do something
    }

我使用这些 channel 进行事件驱动的模拟,因此我必须选择 Event少用time field 。

是否可以检查每个 channel 的值,然后选择要读取的值?因为操作<-chan1从 channel 获取值,并且无法将其推回(只读 channel )。

最佳答案

您可以实现您的 go channel 结构版本。例如,下面的实现就像没有大小限制的 go channel 一样,您可以检查它的第一个元素。

package buffchan

import (
    "container/list"
    "sync"
)

// BufferedChannel provides go channel like interface with unlimited storage
type BufferedChannel struct {
    m *sync.Mutex
    l *list.List
    c *sync.Cond
}

// New Creates new buffer channel
func New() *BufferedChannel {
    m := new(sync.Mutex)
    return &BufferedChannel{
        m: m,
        l: list.New(),
        c: sync.NewCond(m),
    }
}

// Append adds given data at end of channel
func (b *BufferedChannel) Append(v interface{}) {
    b.m.Lock()
    defer b.m.Unlock()

    b.l.PushBack(v)
    b.c.Signal()

}

// Remove removes first element of list synchronously
func (b *BufferedChannel) Remove() interface{} {
    b.m.Lock()
    defer b.m.Unlock()

    for b.l.Len() == 0 {
        b.c.Wait()
    }

    v := b.l.Front()
    b.l.Remove(v)

    return v.Value
}

// Inspect first element of list if exists
func (b *BufferedChannel) Inspect() interface{} {
    b.m.Lock()
    defer b.m.Unlock()

    for b.l.Len() == 0 {
        return nil
    }

    return b.l.Front().Value
}

// AsyncRemove removes first element of list asynchronously
func (b *BufferedChannel) AsyncNonBlocking() interface{} {
    b.m.Lock()
    defer b.m.Unlock()

    for b.l.Len() == 0 {
        return nil
    }

    v := b.l.Front()
    b.l.Remove(v)

    return v.Value
}

关于go - 检查 channel 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47800459/

相关文章:

json - 带有任意键的 json 的 golang 结构

javascript - 在 JavaScript 中实现协程控制流

python - 如何使用状态为 Keras fit_generator 编写生成器?

Java:将 TRUE/FALSE 的所有可能组合添加到列表中

golang 模块名称更改导致本地测试失败

json - 如何从bson文档中呈现json字符串

Go:通过接口(interface)访问结构体的属性{}

Goroutines 一段时间后不回复

go - 无法停止计时器

go - 处理超时并收听 channel