以下代码打开 10,000 个 go routines,它们进行 HTTP 调用、获取响应、关闭响应并写入具有 ID 的 channel 。
在第二个 for 循环中,它从缓冲 channel 中打印出前一个 go 例程的 ID。
这会导致分段冲突,我不明白为什么。
panic :
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x40 pc=0x2293]
代码:
package main
import (
"fmt"
"net/http"
)
func main() {
requests := 10000
ch := make(chan string, requests)
for i := 1; i <= requests; i++ {
go func(iter int) {
fmt.Println(iter)
resp, _ := http.Get("http://localhost:8080/api/project")
resp.Body.Close()
ch <- fmt.Sprint("%i", iter)
}(i)
}
for i := 1; i <= requests; i++ {
fmt.Println(<-ch)
}
}
最佳答案
调用 api 时不检查任何错误。因此,在尝试关闭从未到达的响应时出现错误。
这段代码不会引起 panic :
package main
import (
"fmt"
"net/http"
)
func main() {
requests := 10000
ch := make(chan string, requests)
for i := 1; i <= requests; i++ {
go func(iter int) {
fmt.Println(iter)
resp, err := http.Get("http://localhost:8080/api/project")
if (err == nil) {
resp.Body.Close()
}
ch <- fmt.Sprint(iter)
}(i)
}
for i := 1; i <= requests; i++ {
fmt.Println(<-ch)
}
}
关于go - golang channel 的分段违规,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41858635/