Go 检查是否有人读过围棋频道

Go 检查是否有人读过围棋频道,go,channel,Go,Channel,我们如何设置像go频道上的listener这样的东西,当有人从频道上读到东西时,会通知我们 假设我们有一个序列号用于通道条目,当有人从我们的包中的某个地方从我们的通道读取值时,我们希望将其递减。您可以在手动模式下执行此操作。对消息执行某种ACK标记。 大概是这样的: type Msg struct { Data int ack bool } func (m *Msg) Ack() { m.ack = true } func (m *Msg) Acked() bool

我们如何设置像go频道上的listener这样的东西,当有人从频道上读到东西时,会通知我们


假设我们有一个
序列号
用于通道条目,当有人从我们的包中的某个地方从我们的通道读取值时,我们希望将其递减。

您可以在手动模式下执行此操作。对消息执行某种
ACK
标记。 大概是这样的:

type Msg struct {
    Data int
    ack  bool
}

func (m *Msg) Ack() {
    m.ack = true
}

func (m *Msg) Acked() bool {
    return m.ack
}

func main() {
    ch := make(chan *Msg)
    msg := &Msg{Data: 1}
    go func() {
        for {
            if msg.Acked() {
                // do smth
            }
            time.Sleep(10 * time.Second)
        }
    }()
    ch <- msg

    for msg := range ch {
        msg.Ack()
    }
}
type Msg struct{
数据整型
阿克布尔
}
func(m*Msg)Ack(){
m、 ack=真
}
func(m*Msg)Acked()bool{
返回m.ack
}
func main(){
ch:=制造(成龙*味精)
msg:=&msg{Data:1}
go func(){
为了{
如果msg.Acked(){
//做smth
}
时间。睡眠(10*时间。秒)
}
}()

CH

非缓冲通道同步地切换数据,因此您已经知道数据何时被读取。缓冲区在缓冲区满时工作类似,但否则它们不会阻塞相同的,所以这种方法不会告诉您完全相同的事情。根据您的需要,也可以考虑使用类似于./P>的工具。

ch=make(信道数据)
⋮
为了{
⋮
//提供数据

您可以创建一个通道中继机制,以实时捕获读取事件

例如:

func relayer(in <-chan MyStruct) <-chan MyStruct {
        out := make(chan MyStruct) // non-buffered chan (see below)

        go func() {     
                defer close(out)
                readCountLimit := 10

                for item := range in {
                        out <- item
                        // ^^^^ so this will block until some worker has read from 'out'
                        readCountLimit--
                }
        }()     
        return out      
}

func继电器(通常情况下,您无法收到来自某个频道的另一个goroutine的通知,但您可以构建您的应用程序,这样您就不需要这样做。例如,您可以让一个专用goroutine在频道上发送递增的数字,因此从该频道接收的值是否和数量无关紧要。谢谢,但我一直在寻找cha的解决方案nnels本身,而不是为此包装我的数据。
func relayer(in <-chan MyStruct) <-chan MyStruct {
        out := make(chan MyStruct) // non-buffered chan (see below)

        go func() {     
                defer close(out)
                readCountLimit := 10

                for item := range in {
                        out <- item
                        // ^^^^ so this will block until some worker has read from 'out'
                        readCountLimit--
                }
        }()     
        return out      
}
type MyStruct struct {
        // put your data fields here
}

ch := make(chan MyStruct) // <- original channel - used by producer to write to

rch := relayer(ch) // <- relay channel - used to read from

// consumers
go worker("worker 1", rch)
go worker("worker 2", rch)

// producer
for { ch <- MyStruct{} }