作为一个愚蠢的基本线程练习,我一直在尝试在golang中实现
sleeping barber problem.有渠道这应该很容易,但我遇到了heisenbug.也就是说,当我尝试诊断它时,问题就消失了!
考虑以下. main()函数将整数(或“客户”)推送到商店渠道. barber()阅读商店频道以剪掉“顾客”的头发.如果我将fmt.Print语句插入customer()函数,程序将按预期运行.否则,理发师()永远不会削减任何人的头发.
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) } }
知道正在发生什么吗?