I am trying something similar to the below pattern:
func sendFunc(n int, c chan int) {
for i := 0; i < n; i++ {
c <- i
fmt.Println("Pushed")
}
close(c)
}
func main() {
c := make(chan int, 10)
go sendFunc(10, c)
// Receive from the channel
for i := range c {
fmt.Println(i)
}
}
The output appears to be sync, like this:
Pushed
Pushed
Pushed
Pushed
Pushed
Pushed
Pushed
Pushed
Pushed
Pushed
0
1
2
3
4
5
6
7
8
9
And if I change the buffered channel to a non-buffered channel:
c := make(chan int)
the result seems to be async:
Pushed
0
1
Pushed
Pushed
2
3
Pushed
Pushed
4
5
Pushed
Pushed
6
7
Pushed
Pushed
8
9
Pushed
why it behaves differently?
Updated
So my scenario is that: in the receiver a request will be made every time new data is received from the producer, the result shows that the scheduler does not start receiving until all data has been sent to the channel (given a buffered channel with enough space), unless the producer is paused (e.g. by calling time.sleep()
). Therefore I ended up using the non-buffered channel so that the time to wait for responses and the time to process data in the producer can overlap which leads to better concurrency.