2017-01-25 24 views
0

以下のコードは、HTTPコールを発信し、応答を取得し、応答をクローズし、IDを持つチャネルに書き込む10,000個のgoルーチンを開きます。golangチャネルによるセグメンテーション違反

2番目のforループでは、バッファされたチャネルから前のgoルーチンのIDが出力されます。

これはセグメンテーション違反の原因となり、理由を把握できません。

パニック:

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) 
    } 
} 
+4

をチェックし、エラー:

このコードは、パニックはありません。 – JimB

答えて

3

APIを呼び出すときに、任意のエラーをチェックしません。したがって、到着しなかった応答を閉じるときにエラーが発生します。 、常に

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) 
    } 
} 
関連する問題