Home > Backend Development > Golang > Go Deadlock: Why Does 'throw: all goroutines are asleep' Happen?

Go Deadlock: Why Does 'throw: all goroutines are asleep' Happen?

Mary-Kate Olsen
Release: 2025-01-02 15:03:39
Original
535 people have browsed it

Go Deadlock: Why Does

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

In a Go program, a deadlock occurs when two or more goroutines wait for each other to finish, resulting in a frozen state where no progress can be made. This issue is often reported as "throw: all goroutines are asleep - deadlock!"

Let's analyze a simplified Go program to understand why this deadlock occurs:

package main

import (
    "fmt"
)

func total(ch chan int) {
    res := 0
    for iter := range ch {
        res += iter
    }
    ch <- res
}

func main() {
    ch := make(chan int)
    go total(ch)
    ch <- 1
    ch <- 2
    ch <- 3
    fmt.Println("Total is ", <-ch)
}
Copy after login

In this program, the total function calculates the sum of the numbers sent via the ch channel and sends the result back on the same channel. The deadlock arises because the following conditions are met:

  • The total function blocks inside the for loop waiting for more input via ch (with the range keyword).
  • The main function sends three values to ch but does not close the channel.
  • Since the total function is still waiting for more input, it does not send the result back on ch.
  • The main function blocks at the fmt.Println line waiting for the result from ch.

This creates a deadlock situation where both goroutines (the one running total and the one in main) are waiting for the other to act, leading to the "throw: all goroutines are asleep" error.

To resolve this deadlock, we can close the ch channel in the main function after sending the last value:

ch <- 3
close(ch)
Copy after login

Closing the channel signals to the total goroutine that there is no more input, allowing it to complete its calculation and send the result back on ch.

The above is the detailed content of Go Deadlock: Why Does 'throw: all goroutines are asleep' Happen?. 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