Home >Backend Development >Golang >How to Solve the 'All goroutines are Asleep' Deadlock in Go?

How to Solve the 'All goroutines are Asleep' Deadlock in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-24 16:11:10919browse

How to Solve the

Dealing with a Deadlock in Goroutines: "All goroutines are Asleep"

Understanding the Deadlock

In the provided code, you encounter a deadlock due to the lack of proper channel handling. The problem arises in the UnloadTrucks function, where you indefinitely block waiting for trucks to arrive in the ch channel. However, the main goroutine never closes this channel, resulting in an endless wait.

Addressing the Deadlock

To resolve the deadlock, you must close the ch channel once all trucks have been loaded and sent through the channel. This can be achieved using a WaitGroup to track the goroutines that are loading trucks:

go func() {
    wg.Wait()
    close(ch)
}()

When all goroutines have completed loading trucks, the channel ch will be closed, allowing UnloadTrucks to proceed.

Rewritten Code:

package main

import (
    "fmt"
    "sync"
    "time"
)

type Item struct {
    name string
}

type Truck struct {
    Cargo []Item
    name  string
}

func UnloadTrucks(c chan Truck) {

    for t := range c {
        fmt.Printf("%s has %d items in cargo: %s\n", t.name, len(t.Cargo), t.Cargo[0].name)
    }

}

func main() {
    trucks := make([]Truck, 2)

    ch := make(chan Truck)

    var wg sync.WaitGroup

    for i, _ := range trucks {

        trucks[i].name = fmt.Sprintf("Truck %d", i+1)

        fmt.Printf("Building %s\n", trucks[i].name)
    }

    for t := range trucks {
        wg.Add(1)
        go func(tr Truck) {

            itm := Item{}
            itm.name = "Groceries"

            fmt.Printf("Loading %s\n", tr.name)
            tr.Cargo = append(tr.Cargo, itm)
            ch <- tr
            wg.Done()

        }(trucks[t])
    }

    time.Sleep(50 * time.Millisecond)
    fmt.Println("Unloading Trucks")
    UnloadTrucks(ch)

    fmt.Println("Done")
}

The above is the detailed content of How to Solve the 'All goroutines are Asleep' Deadlock in Go?. 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