在发生某些事件之前,请不要向通道写入内容。

huangapple go评论83阅读模式
英文:

Don't write to a channel until something happens

问题

我目前有这样的代码:

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 {
        // 如何暂停向该通道写入更多内容?它刚刚被解除阻塞
        r.processEvent(t)
        // 取消暂停向该通道写入更多内容 - 现在给我发送下一个东西。
    }
}

我的问题是,告诉通道在ProcessEvent完成之前停止向其写入更多内容的最佳方法是什么?由于process方法刚刚从r.reqChan中获取了一些内容,我不希望Foo Work()processEvent完成之前向rpChan通道写入更多数据。我唯一想到的方法是引入另一个通道,在r.processEvent(t)完成时设置该通道,然后process将从该通道读取以继续。是否有更好的方法?也许是使用IPC队列?

英文:

I currently have something like this

type Foo struct {
	rpChan        chan&lt;- *Data
}

func (s *Foo) Work() {
    ......
	for event := range watch.ResultChan() {
		s.rpChan &lt;- &amp;sr
        ...........
        ...........
	}
}

Then somewhere else I am pulling data from that channel (rpChan) like this

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.  
	}
}

My question is what would be the best way to tell the channel to stop writing more stuff to it until ProcessEvent is completed ? Since the process method just pulled something from r.reqChan, I do not want Foo Work() to write more data to the rpChan channel until processEvent is completed. The only thought that I have is introducing another channel that gets set when r.processEvent(t)
is completed and then process would read from that channel to continue. Is there a better approach to this ? Perhaps a IPC queue ?

答案1

得分: 4

规范中提到:“如果容量为零或不存在,则通道是无缓冲的,只有在发送方和接收方都准备好时,通信才会成功。”

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

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

英文:

The specification says If the capacity is zero or absent, the channel is unbuffered and communication succeeds only when both a sender and receiver are ready.

Make r.reqChan an unbuffered channel to ensure that a send to r.reqChan does not complete while the receiving goroutine executes r.processEvent(t).

A goroutine can only do one thing at a time. If the receiving goroutine is executing r.processEvent(t), then the receiving goroutine is not executing the receive operation implicit in range. It follows that a send does not complete while the receiving goroutine executes r.processEvent(t).

huangapple
  • 本文由 发表于 2022年11月3日 07:35:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/74296709.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定