Home >Backend Development >Golang >Why Does My Go Code Produce a 'fatal error: all goroutines are asleep - deadlock!' Error with sync.WaitGroup?

Why Does My Go Code Produce a 'fatal error: all goroutines are asleep - deadlock!' Error with sync.WaitGroup?

Linda Hamilton
Linda HamiltonOriginal
2024-12-09 21:17:11272browse

Why Does My Go Code Produce a

"All Goroutines Asleep" Error When Using sync.WaitGroup

In your code, you are encountering a "fatal error: all goroutines are asleep - deadlock!" message. This occurs because you are passing a copy of the WaitGroup to each goroutine instead of a reference to the original.

As per the documentation, WaitGroup requires you to pass a pointer to the variable instead of the variable itself. When you pass the actual WaitGroup value, Go makes a copy, resulting in multiple WaitGroup instances with different counts.

The updated code should be:

import "sync"

func doWork(wg *sync.WaitGroup) error {
    defer wg.Done()
    // Do some heavy lifting... request URL's or similar
    return nil
}

func main() {
    wg := &sync.WaitGroup{}
    for i := 0; i < 10; i++ {
        wg.Add(1)
        go doWork(wg)
    }
    wg.Wait()
}

By passing a pointer, all goroutines reference the same WaitGroup. When they call Done(), it decrements the count in the original WaitGroup, resulting in the expected behavior.

The above is the detailed content of Why Does My Go Code Produce a 'fatal error: all goroutines are asleep - deadlock!' Error with sync.WaitGroup?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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