doupa1883 2019-06-21 15:38
浏览 13

通道何时阻止goroutine

If I define a channel without buffer and write one data into it, does it block immediately(so that the kernel will look for another unblocked goroutine that reads from the channel), or does it continues execution and blocks when the next time some code tries to write into the channel again, when it hasn't been read yet?

Below are two pieces of codes I wrote to research on this problem.

code1:

package main

import "fmt"

func main() {
    c := make(chan int)
    go func() {
        for i := 0;i < 3; i++ {
            c <- i
            fmt.Printf("number %v inserted into channel
", i)
        }
    }()
    for i := 0; i < 3; i++ {
        fmt.Printf("number poped from channel %v
", <-c)
    }
}

The output is like this:

number 0 inserted into channel
number poped from channel 0
number poped from channel 1
number 1 inserted into channel
number 2 inserted into channel
number poped from channel 2

After the first time c is written into, this goroutine seems to continue to be executed, since "number 0 inserted into channel" was printed.

code2:

package main

import "fmt"

func main() {
    c := make(chan int)
    c <- 2
    fmt.Println("Something is written into channel")
    <-c
}

This piece of code cannot run correctly since a deadlock error is reported at runtime.

fatal error: all goroutines are asleep - deadlock!

From my view, when c <-2 is executed, the goroutine is blocked(if it's not blocked, the fmt.Println line will be executed and continuing executing will unlock c at <-c). When this goroutine is blocked, the kernel searches other goroutines and find none, so it reports a deadlock error.

In summary, in the first piece of code I conclude that writting to a channel doesn't block the goroutine immediately but from the second piece of code it does. Where did I get it wrong and when does a channel blocks a goroutine?

  • 写回答

1条回答 默认 最新

  • duanshan2988 2019-06-21 15:40
    关注

    Sending to a channel with no available buffer space blocks the sender until the send can complete; receiving from a channel with no available messages blocks the receiver until the receive can complete. An unbuffered channel never has buffer space - sends block until something receives and vice-versa. This is covered in the Tour of Go: https://tour.golang.org/concurrency/2

    Remember that your code is concurrent so you can't read too much into the order of output statements. A goroutine can be put to sleep in between the send/receieve operation and when your message is printed to stdout.

    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀