【发布时间】:2012-04-26 09:32:13
【问题描述】:
作为一个愚蠢的基本线程练习,我一直在尝试在 golang 中实现 sleeping barber problem。有了频道,这应该很容易,但我遇到了一个 heisenbug。也就是说,当我尝试诊断它时,问题就消失了!
考虑以下问题。 main() 函数将整数(或“客户”)推送到 shop 通道。 barber() 读取shop 频道以剪掉“客户”的头发。如果我将fmt.Print 语句插入customer() 函数,程序将按预期运行。否则,barber() 绝不会剪别人的头发。
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)
}
}
知道发生了什么吗?
【问题讨论】:
标签: concurrency go goroutine