Why does GO protocol cause deadlock?

package main

import (
    "fmt"
)

func f1(in chan int) {
    fmt.Println(<-in)
}

func main() {
    out := make(chan int)
    out <- 2
    go f1(out)
}

Why does this cause deadlocks? How to solve it?

Nov.05,2021

change it to this:

package main

import (
    "fmt"
)

func f1(in chan int) {

    fmt.Println(<-in)
}

func main() {

    out := make(chan int)
    go f1(out)
    out <- 2
}

because your make is an unbuffered chan
, chan needs to be consumed before it can be written, otherwise it will block
so there is a second way to generate buffered chan:

make(chan int, 1)

out the queue is unbuffered and the main thread will block here. There are two solutions.

first, set the buffer:

package main

import (
    "fmt"
)

func f1(in chan int) {
    fmt.Println(<-in)
}

func main() {
    out := make(chan int,1)
    out <- 2
    go f1(out)
}

second, advance go F1 (out) :

package main

import (
    "fmt"
)

func f1(in chan int) {
    fmt.Println(<-in)
}

func main() {
    out := make(chan int)
    go f1(out)
    out <- 2
}

unbuffered channel transceivers are blocked. If you send 2 in the main goroutine, it is blocked all the time.

waiting for someone to receive it, of course it will be deadlocked


you need to understand two concepts, an unbuffered channel and a cached channel.

  1. ch: = make (chan int) and ch: = make (chan int, 0) both create unbuffered channels.
  2. ch: = make (chan int, x) , where x > 0, the cached channel is established.

the difference between the two is that the unbuffered channel is Synchronize. When writing data, there must be a co-program to read the data before returning, and a cache channel is semi-asynchronous. When the buffer is not full, write to the buffer can be returned as long as there is still space in the cache.

this is an unbuffered channel. When writing data to out, co-program F1 has not been created, so there is no co-program to read out data, resulting in program deadlock.

Menu