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.
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.
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!