英文:
golang have weird behavior in deadlock detection
问题
package main
import (
"log"
"net/http"
)
func useless_func(address string) []byte {
http.Get("https://www.google.com")
return nil
}
func test_a(test_channel chan int) {
test_channel <- 1
return
}
func test() {
test_channel := make(chan int)
for i := 0; i < 10; i++ {
go test_a(test_channel)
}
for {
log.Println(<-test_channel)
}
}
func main() {
test()
}
这段代码不会因为死锁而中断。我在 Linux 4.1.6-1 和 3.16.0-4 上使用 go 1.5.1 amd64 运行了这段代码,并得到了相同的结果。但是,如果我删除 useless_func
函数,或者使用 go 1.4.3 版本,或者在 Windows 上运行,它将正常执行。这真的很奇怪,如果有人能解释一下吗?
英文:
package main
import (
"log"
"net/http"
)
func useless_func(address string) []byte {
http.Get("https://www.google.com")
return nil
}
func test_a(test_channel chan int) {
test_channel <- 1
return
}
func test() {
test_channel := make(chan int)
for i := 0; i < 10; i++ {
go test_a(test_channel)
}
for {
log.Println(<-test_channel)
}
}
func main() {
test()
}
this code would not break because of deadlock, I try this code under Linux 4.1.6-1 and 3.16.0-4 with go 1.5.1 amd64 and got same result. but if i delete useless_func or use go 1.4.3 or run this under windows,it would perform well. this is really weird, if anyone could explain this?
答案1
得分: 5
Dominik Honnef在回应Go 1.5.1的问题##12734时提供了答案:
> dominikh: 这个问题实际上出现在使用cgo(net包使用了cgo,忽略细节)。当使用cgo时,Go的死锁检测无法正常工作,因为C世界可能随时调用Go函数,所以理论上不存在死锁;我们可能只是无限期地等待外部函数的调用。
英文:
Dominik Honnef provides the answer in response to issue ##12734 for Go 1.5.1:
> dominikh: The issue really lies with using cgo (which net uses, ignoring the details). When using cgo, the Go deadlock detection cannot function properly, because C world might call Go functions at any time, so in theory no deadlock exists; we might just be waiting for an external function call indefinitely.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论