go - golang channel 的分段违规

标签 go channel

以下代码打开 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/

相关文章:

Golang 为 html 选择标签中的选项构造月份

java - 请帮助我理解 Java 中的 Pusher websocket API

常规处理 channel 范围

go - 模板部分呈现为纯文本

go - 在我的案例中,如何以正确的方式测试方法?

http - 在 Go http 处理程序中处理 Write 调用错误的最佳方法

go - 如果 sync.WaitGroup 类型的 Wait() 方法阻塞,因此不是异步的,为什么要使用它?

encryption - ANT+ 单 channel 加密示例

concurrency - Func 不会运行;增量 channel

dictionary - 从 golang 中的 channel 响应填充 map 值