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 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)