Home > Backend Development > Golang > Go Deadlocks: How to Avoid the 'all goroutines are asleep' Error?

Go Deadlocks: How to Avoid the 'all goroutines are asleep' Error?

Linda Hamilton
Release: 2024-12-27 13:06:18
Original
836 people have browsed it

Go Deadlocks: How to Avoid the

Deadlock in Go: "throw: all goroutines are asleep"

A goroutine deadlock occurs when all running goroutines are waiting for each other to complete. In the provided Go code, a deadlock arises due to the unclosed channel ch.

The total function continuously waits for new values on the ch channel using a range loop. Since the ch channel is never closed, the loop will never terminate. This means that the goroutine responsible for executing this function will never finish.

Meanwhile, in the main function, the program attempts to send values to the ch channel and receive the result. However, since the total goroutine is waiting indefinitely, it can't process the sent values and send back the result. This causes the program to deadlock.

To resolve this deadlock, the ch channel must be closed after sending all the values. This will signal the total function to stop waiting for new values and calculate the result.

Here's a modified version of the code with the channel closure:

package main

import (
    "fmt"
)

func total(in chan int, out chan int) {
    res := 0
    for iter := range in {
        res += iter
    }
    out <- res // sends back the result
}

func main() {
    ch := make(chan int)
    rch := make(chan int)
    go total(ch, rch)
    ch <- 1
    ch <- 2
    ch <- 3
    close(ch) // this will end the loop in the total function
    result := <-rch // waits for total to give the result
    fmt.Println("Total is ", result)
}
Copy after login

Now, the goroutine running total will correctly perform the summation and send the result back to main, preventing a deadlock.

The above is the detailed content of Go Deadlocks: How to Avoid the 'all goroutines are asleep' Error?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template