Golang在死锁检测方面有奇怪的行为。

huangapple go评论81阅读模式
英文:

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 (
	&quot;log&quot;
	&quot;net/http&quot;
)

func useless_func(address string) []byte {
	http.Get(&quot;https://www.google.com&quot;)
	return nil
}
func test_a(test_channel chan int) {
	test_channel &lt;- 1
	return
}

func test() {
	test_channel := make(chan int)
	for i := 0; i &lt; 10; i++ {
		go test_a(test_channel)
	}
	for {
		log.Println(&lt;-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.

huangapple
  • 本文由 发表于 2015年9月24日 16:15:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/32756524.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定