BufBills
BufBills

Reputation: 8103

go channel, seems all right, but it gets deadlock

package main
import "fmt"
import "time"

func main() {
     c := make(chan int)
     c <- 42    // write to a channel

     val := <-c // read from a channel
     println(val)
}

I think c <- 42 put 42 to channel c, then val := <-c put value in c to val. but why does it get deadlock?

Upvotes: 1

Views: 81

Answers (1)

James Henstridge
James Henstridge

Reputation: 43899

You have created an unbuffered channel. So the statement c <- 42 will block until some other goroutine tries to receive a value from the channel. Since no other goroutine is around to do this, you got a deadlock. There are two ways you could fix this:

  1. Perform the receive in a different goroutine.
  2. Add a buffer to the channel. For example, c := make(chan int, 1) would allow you to send a single value on the channel without blocking.

Upvotes: 5

Related Questions