Home > Article > Backend Development > A goroutine that prints odd and even numbers alternately gets stuck in deadlock
"The goroutine that alternately prints odd and even numbers falls into a deadlock" is a common problem in concurrent programming. When using goroutine for concurrent operations, if there is no correct synchronization mechanism, it can easily lead to deadlock. Deadlock is a state in which two or more processes (or goroutines) are unable to continue execution because they are waiting for each other to release resources. This article will introduce the cause of this problem and provide solutions to help developers better understand the deadlock problem in concurrent programming.
I am currently learning golang. I want to check how golang channels work. I created a program where two goroutines will alternately print odd and even numbers. Even though the program prints correctly, it still shows a deadlock error at the end. It's not clear from the error message what causes this problem.
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() }
[edit] thanks for your replies. I wrote the following code to solve the problem.
func main() { even := make(chan bool) odd := make(chan bool) done := make(chan bool) //var wait sync.WaitGroup //wait.Add(2) go func() { for i := 0; i <= 10; i += 2 { <-even print("Even ====>") println(i) odd <- true } close(odd) close(even) done <- true // wait.Done() }() go func() { for i := 1; ; i += 2 { _, ok := <-odd if !ok { //wait.Done() return } print("Odd ====>") println(i) select { case even <- true: case <-done: return } } }() even <- true //wait.Wait() <-done }
The problem can be solved in the following ways
select
ing when writing even
(line 28) The above is the detailed content of A goroutine that prints odd and even numbers alternately gets stuck in deadlock. For more information, please follow other related articles on the PHP Chinese website!