为什么带有goroutines的for循环会导致数据丢失

为什么带有goroutines的for循环会导致数据丢失,go,struct,goroutine,Go,Struct,Goroutine,好的,我有两位代码。首先是一个简单的for循环,非常有效 package main import ( "context" "encoding/json" "fmt" "log" "os" elasticsearch "github.com/elastic/go-elasticsearch/v7" "github.com/elastic/go-elasticsearch/v7/esapi" "github.com/mitchell

好的,我有两位代码。首先是一个简单的for循环,非常有效

package main

import (
    "context"
    "encoding/json"
    "fmt"
    "log"
    "os"

    elasticsearch "github.com/elastic/go-elasticsearch/v7"
    "github.com/elastic/go-elasticsearch/v7/esapi"
    "github.com/mitchellh/mapstructure"
)

type Esindices struct {
    Health       string `json:"health"`
    Status       string `json:"status"`
    Index        string `json:"index"`
    Uuid         string `json:"uuid"`
    Pri          string `json:"pri"`
    Rep          string `json:"rep"`
    DocsCount    string `json:"docs.count"`
    DocsDeleted  string `json:"docs.deleted"`
    StoreSize    string `json:"store.size"`
    PriStoreSize string `json:"pri.store.size"`
}

func main() {

    var r []map[string]interface{}

    es, err := elasticsearch.NewDefaultClient()
    if err != nil {
        log.Fatalf("Error creating client: %s", err)
    }

    req := esapi.CatIndicesRequest{
        Format: "json",
        Pretty: false,
    }

    res, err := req.Do(context.Background(), es)
    if err != nil {
        log.Fatalf("Error getting response: %s", err)
    }

    defer res.Body.Close()

    if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
        log.Printf("Error parsing the response body: %s", err)
    }

    indexSlice := make([]*Esindices, len(r))

    for i, element := range r {
        result := &Esindices{}
        cfg := &mapstructure.DecoderConfig{
            Metadata: nil,
            Result:   &result,
            TagName:  "json",
        }
        decoder, _ := mapstructure.NewDecoder(cfg)
        decoder.Decode(element)
        indexSlice[i] = result
    }

    thisisjson, err := json.MarshalIndent(indexSlice, "", " ")
    if err != nil {
      log.Fatal("Can't encode to JSON", err)
    }


    fmt.Fprintf(os.Stdout, "%s", thisisjson)
大部分内容都是不言自明的,但为了澄清这一点,我正在使用Elasticsearch客户端和api.cat.indexs api获取本地Elasticsearch安装中所有索引的列表,然后将它们存储为
map[string]interface{}
的数组,然后循环将它们添加到结果结构的切片中。实际上,这很好,但我想注意性能,虽然我不能提高请求本身的延迟,但我肯定可以提高循环的性能,至少我认为我应该能够做到

所以当我尝试下面的方法时,我得到了奇怪的结果

var wg sync.WaitGroup
defer wg.Wait()
for i, element := range r {
    wg.Add(1)
    go func(i int, element map[string]interface{}) {
        defer wg.Done()
        result := Esindices{}
        cfg := &mapstructure.DecoderConfig{
            Metadata: nil,
            Result:   &result,
            TagName:  "json",
        }
        decoder, _ := mapstructure.NewDecoder(cfg)
        decoder.Decode(element)
        indexSlice[i] = result
    }(i, element)
}
具体来说,问题是,片中元素的键的某些值是空的。这让我觉得代码试图添加到切片中,但即使没有完成,它也在传递


想法?

在for循环的末尾使用
wg.Wait
而不是
defer wg.Wait
。在for循环完成之后,您就在for循环中使用goroutine构造的数据,而不是在使用该数据之前等待所有goroutine完成

使用
defer wg.Wait
时,等待发生在函数末尾。使用数据的for循环对不完整的数据进行操作,因为goroutines仍在运行


在for循环结束时使用
wg.Wait
时,首先等待所有goroutine结束,然后使用它们生成的数据。

而不是
defer wg.Wait
,在for循环结束时使用
wg.Wait
。在for循环完成之后,您就在for循环中使用goroutine构造的数据,而不是在使用该数据之前等待所有goroutine完成

使用
defer wg.Wait
时,等待发生在函数末尾。使用数据的for循环对不完整的数据进行操作,因为goroutines仍在运行


在for循环结束时使用
wg.Wait
时,首先等待所有goroutine结束,然后使用它们生成的数据。

这样做了!您是否介意在最后进一步推断一下
defer wg.Wait()
wg.Wait()
之间的区别?信息量非常丰富。我想这对其他人会有帮助的。他做到了!您是否介意在最后进一步推断一下
defer wg.Wait()
wg.Wait()
之间的区别?信息量非常丰富。我认为这将对其他人有所帮助