【问题标题】:Issue modifying map from goroutine func从 goroutine func 修改 map 的问题
【发布时间】:2023-04-08 02:24:01
【问题描述】:
scores := make(map[string]int)
percentage := make(map[string]float64)
total := 0

for i, ans := range answers {
    answers[i] = strings.ToLower(ans)
}

wg := sync.WaitGroup{}

go func() {
    wg.Add(1)

    body, _ := google(question)

    for _, ans := range answers {
        count := strings.Count(body, ans)
        total += count
        scores[ans] += 5 // <------------------- This doesn't work
    }

    wg.Done()
}()

这是一段 sn-p 代码,我的问题是,我无法修改分数,我尝试过使用指针,我尝试过正常操作,我尝试过将其作为参数传递。

【问题讨论】:

    标签: multithreading pointers go maps goroutine


    【解决方案1】:

    Package sync

    导入“同步”

    type WaitGroup

    WaitGroup 等待一组 goroutine 完成。主要的 goroutine 调用 Add 来设置要等待的 goroutine 的数量。然后 每个 goroutine 运行并在完成时调用 Done。同时 时间,Wait 可以用来阻塞,直到所有的 goroutine 都完成。


    您向我们提供了一段无法正常工作的代码。见How to create a Minimal, Complete, and Verifiable example.

    作为猜测,您对sync.WaitGroup 的使用看起来很奇怪。例如,通过简单地按照 sync.Waitgroup 文档中的说明进行操作,我会期待以下内容:

    package main
    
    import (
        "fmt"
        "strings"
        "sync"
    )
    
    func google(string) (string, error) { return "yes", nil }
    
    func main() {
        question := "question?"
        answers := []string{"yes", "no"}
    
        scores := make(map[string]int)
        total := 0
    
        wg := sync.WaitGroup{}
        wg.Add(1)
        go func() {
            defer wg.Done()
    
            body, _ := google(question)
            for _, ans := range answers {
                count := strings.Count(body, ans)
                total += count
                scores[ans] += 5 // <-- This does work
            }
        }()
        wg.Wait()
    
        fmt.Println(scores, total)
    }
    

    游乐场:https://play.golang.org/p/sZmB2Dc5RjL

    输出:

    map[yes:5 no:5] 1
    

    【讨论】:

    • 哦,我明白了,真是一个菜鸟的错误,我过去什至做过这个,应该用种族参数跑,非常感谢你:) 对不起代码 sn-p ,这是深夜,我第一次使用 StackOverflow,我会确保下次提供完整的工作代码,而不是没有上下文的随机 sn-p。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 2018-01-15
    • 1970-01-01
    • 2011-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多