我有两个只读 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/