dongyuan6949 2012-04-14 02:58
浏览 109
已采纳

打印到标准输出会导致阻塞的goroutine运行?

As a silly basic threading exercise, I've been trying to implement the sleeping barber problem in golang. With channels this should be quite easy, but I've run into a heisenbug. That is, when I try to diagnose it, the problem disappears!

Consider the following. The main() function pushes integers (or "customers") onto the shop channel. barber() reads the shop channel to cut "customers'" hair. If I insert a fmt.Print statement into the customer() function, the program runs as expected. Otherwise, barber() never cuts anyone's hair.

package main

import "fmt"

func customer(id int, shop chan<- int) {
    // Enter shop if seats available, otherwise leave
    // fmt.Println("Uncomment this line and the program works")
    if len(shop) < cap(shop) {
        shop <- id
    }
}

func barber(shop <-chan int) {
    // Cut hair of anyone who enters the shop
    for {
        fmt.Println("Barber cuts hair of customer", <-shop)
    }
}

func main() {
    shop := make(chan int, 5) // five seats available
    go barber(shop)
    for i := 0; ; i++ {
        customer(i, shop)
    }
}

Any idea what's afoot?

  • 写回答

2条回答 默认 最新

  • doushou8730 2012-04-14 04:52
    关注

    The problem is the way Go's scheduler is implemented. The current goroutine can yield to other goroutines only when it makes a system call or a blocking channel operation. fmt.Println makes a system call, giving the goroutine an opportunity to yield. Otherwise it doesn't have one.

    In practice this doesn't often matter, but for small problems like this it can sometimes crop up.

    Also, a more idiomatic, less racy way of doing a non-blocking send on a channel is:

    func customer(id int, shop chan<- int) {
        // Enter shop if seats available, otherwise leave
        select {
        case shop <- id:
        default:
        }
    }
    

    The way you're doing it, a customer could end up waiting outside of the barber shop since by the time you actually do the send, len(shop) may have changed.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 android报错 brut.common.BrutException: could not exec (exit code = 1)
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择
  • ¥15 部分网页页面无法显示!