Sobes.tech
Senior

package main import ( "fmt" ) func main() { c := make(chan string, 1) go fmt.Println(<-c) c <- "Hello World!" fmt.Println("Exit!") } fatal error: all goroutines are asleep - deadlock! goroutine 1 [chan receive]: main.main() /tmp/sandbox[phone]/prog.go:10 +0x3a Program exited: status 2.

sobes.tech AI

Answer from AI

This code causes a deadlock due to the order of operations between the channel and the goroutine.

Analysis:

  • The channel c is created with a buffer of 1 element.
  • A goroutine is started, which attempts to read from the channel: <-c.
  • The main goroutine tries to send the string c <- "Hello World!" into the channel.

The problem is that the goroutine reading from the channel blocks on the read operation, waiting for data. However, the main goroutine attempts to send data into the channel after starting the goroutine. But because the reading goroutine does not receive the data in time, and the main thread blocks on sending, a deadlock occurs.

To fix this, you should change the order of operations or use a properly buffered channel. For example, you can first send data into the channel, then start the goroutine that reads it:

package main

import (
	"fmt"
)

func main() {
	c := make(chan string, 1)

	c <- "Hello World!"
	go fmt.Println(<-c)

	fmt.Println("Exit!")
}

Alternatively, use non-blocking send and receive to avoid deadlocks.