登录
首页 >  Golang >  Go问答

在特定情况下,避免向通道中写入

来源:stackoverflow

时间:2024-03-02 23:09:25 130浏览 收藏

你在学习Golang相关的知识吗?本文《在特定情况下,避免向通道中写入》,主要介绍的内容就涉及到,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!

问题内容

我目前有这样的东西

type foo struct {
    rpchan        chan<- *data
}

func (s *foo) work() {
    ......
    for event := range watch.resultchan() {
        s.rpchan <- &sr
        ...........
        ...........
    }
}

然后我在其他地方从该通道(rpchan)提取数据,如下所示

func (r *Bar) process() {
    for t := range r.reqChan {
          //How do I Pause writing more stuff to this channel ? It has just been unblocked
          r.processEvent(t)
          //Un-Pause writing more stuff to this channel - Now send me the next thing.  
    }
}

我的问题是,在 processevent 完成之前告诉通道停止写入更多内容的最佳方法是什么?由于 process 方法只是从 r.reqchan 中提取一些内容,因此我不希望 foo work() 将更多数据写入 rpchan 通道,直到 processevent 完成。我唯一的想法是引入另一个通道,该通道在 r.processevent(t) 时设置 完成后,process 将从该通道读取数据以继续。有更好的方法吗?也许是一个 ipc 队列?


正确答案


specification says 如果容量为零或不存在,则通道不缓冲,并且仅当发送方和接收方都准备好时通信才会成功。

r.reqChan 设为无缓冲通道,以确保在接收 Goroutine 执行 r.processEvent(t) 时,向 r.reqChan 的发送不会完成。

一个 goroutine 一次只能做一件事。如果接收 Goroutine 正在执行 r.processEvent(t),则接收 Goroutine 不会执行 range 中隐式的接收操作。因此,当接收 Goroutine 执行 r.processEvent(t) 时,发送未完成。

今天关于《在特定情况下,避免向通道中写入》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>