Building an asynchronous architecture with a channel for reading elements and a channel for donning

Viewed 20

Faced such a situation that I'm not sure how it will behave in golang when sequentially reading from a channel, which should end with a done signal from the "done channel". Here is an example that characterizes my code:

func f() {
    doneCh := make(chan struct{})
    trafficCh := make(chan interface{})

    go write(doneCh, trafficCh)
    read(doneCh, trafficCh)
}


func write(doneCh chan<- struct{}, sendCh chan<- interface{}) {
    defer func() {
        doneCh <- struct{}{}
    }()

    for {
        // Send something in sendCh
    }
}


func read(doneCh <-chan struct{}, recvCh <-chan interface{}) {
    for {
        select {
            case <-doneCh:
                return
            case item := <-recvCh:
                // Something do with item
        }
    }
}

According to the standard, if select statment has received several messages in different channels, then it selects a random one. Is it possible that when select selects a channel, it will see a message in both doneCh and recvCh, i.e. undefined behavior will occur, and we can end the read without reading all the elements.

I want to build reading async architecture without missing elements.

0 Answers
Related