英文:
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<- *Data
}
func (s *Foo) Work() {
......
for event := range watch.ResultChan() {
s.rpChan <- &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)
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论