I wrote the code below to check the distribution of channel elements between two functions:
<code>package main
import (
"fmt"
)
func a(ch chan int, done chan struct{}) {
for i := range ch {
fmt.Println(i, "got a")
}
done <- struct{}{}
}
func b(ch chan int, done chan struct{}) {
for i := range ch {
fmt.Println(i, "got b")
}
done <- struct{}{}
}
func main() {
ch := make(chan int, 10)
done := make(chan struct{}, 2)
go b(ch, done)
go a(ch, done)
for i := 0; i < 10; i++ {
ch <- i
}
close(ch)
<-done
<-done
}
</code>
<code>package main
import (
"fmt"
)
func a(ch chan int, done chan struct{}) {
for i := range ch {
fmt.Println(i, "got a")
}
done <- struct{}{}
}
func b(ch chan int, done chan struct{}) {
for i := range ch {
fmt.Println(i, "got b")
}
done <- struct{}{}
}
func main() {
ch := make(chan int, 10)
done := make(chan struct{}, 2)
go b(ch, done)
go a(ch, done)
for i := 0; i < 10; i++ {
ch <- i
}
close(ch)
<-done
<-done
}
</code>
package main
import (
"fmt"
)
func a(ch chan int, done chan struct{}) {
for i := range ch {
fmt.Println(i, "got a")
}
done <- struct{}{}
}
func b(ch chan int, done chan struct{}) {
for i := range ch {
fmt.Println(i, "got b")
}
done <- struct{}{}
}
func main() {
ch := make(chan int, 10)
done := make(chan struct{}, 2)
go b(ch, done)
go a(ch, done)
for i := 0; i < 10; i++ {
ch <- i
}
close(ch)
<-done
<-done
}
The output:
<code>0 got a
1 got a
2 got a
3 got a
4 got a
5 got a
6 got a
</code>
<code>0 got a
1 got a
2 got a
3 got a
4 got a
5 got a
6 got a
</code>
0 got a
1 got a
2 got a
3 got a
4 got a
5 got a
6 got a
It turns out, that in 100% all elements will get func a()
. If I run this code from Go Playground – func b()
get only the 1st element. I expected that the distribution would be much more equal. Could you help me understand why does it happens?
New contributor
Warh40k is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.