Home > Back-end >  Don't write to a channel until something happens
Don't write to a channel until something happens

Time:11-04

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 ?

CodePudding user response:

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

  •  Tags:  
  • go
  • Related