Senior
peamine pakett import ( "fmt" ) func main() { c := make(chan string) go fmt.Println(<-c) c <- "Tere, maailm!" fmt.Println("Väljund!") } fatali viga: kõik gorutinid magavad - deadlock! goroutine 1 [kanali vastuvõtt]: main.main() /tmp/sandbox[phone]/prog.go:10 +0x3a Programm lõpetas: olek 2.
sobes.tech AI
Vastus AI-lt
The fatal error: all goroutines are asleep - deadlock! error occurs when all goroutines are blocked and none can continue.
In this code:
c := make(chan string)
go fmt.Println(<-c)
c <- "Hello World!"
fmt.Println("Exit!")
The channel c is created without a buffer, so send (c <-) and receive (<-c) operations must happen simultaneously.
Explanation:
- The goroutine
go fmt.Println(<-c)tries to receive a value from channelc. - The main goroutine tries to send the value
"Hello World!"to channelc.
However, since fmt.Println(<-c) runs in a separate goroutine and the send occurs in the main goroutine, it is possible that the receive goroutine is not yet ready to receive data, and the main goroutine blocks on send.
As a result, both goroutines block: one waiting to send, the other to receive, but neither can continue — a deadlock occurs.
To fix this, you can:
- Make the channel buffered, for example
c := make(chan string, 1), so that the send does not block. - Or change the order of operations, send first, then receive.
Example with buffer:
c := make(chan string, 1)
go fmt.Println(<-c)
c <- "Hello World!"
fmt.Println("Exit!")
Now the program will run without deadlock.