I am currently learning golang. I wanted to check how golang channels work. I have created a program where two goroutines will print odd and even numbers alternatively. Even though the program is printing correctly, it is showing a deadlock error at the end. It is not clear from error message what is causing this issue. https://go.dev/play/p/Eg8vH845cNL
>Solution :
Just in case you don’t end up linking your code, here it is for future readers
package main
import "sync"
func main() {
even := make(chan bool)
odd := make(chan bool)
go func() {
defer close(odd)
for i := 0; i <= 10; i += 2 {
<-even
print("Even ====>")
println(i)
odd <- true
}
}()
var wait sync.WaitGroup
wait.Add(1)
go func() {
for i := 1; i <= 10; i += 2 {
_, ok := <-odd
if !ok {
wait.Done()
return
}
print("Odd ====>")
println(i)
even <- true
}
}()
even <- true
wait.Wait()
}
The deadlock is likely quite easy to figure that it occurs here odd <- true
as a result of a write into an unbuffered (or filled up) channel.
On the last iteration of your second goroutine having this loop for i := 1; i <= 10; i += 2 {
, the channel odd
has been written into already by the first goroutine but the second goroutine can’t read it because the iteration condition no longer matches because i + 2 = 11
at that particular iteration and 11 > 10
which causes the iteration to stop and the channel to stay filled.
Now, the other goroutine trying to write into the odd
channel gets blocked as a result and stays blocked forever but since the runtime can easily detect this…it yields a deadlock pretty quickly afterward.