multithreading - 从 goroutine func 发出修改映射

标签 multithreading pointers go maps goroutine

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()
}()

这是一段代码,我的问题是,我无法修改分数,我试过使用指针,我试过正常进行,我试过将它作为参数传递。

最佳答案

Package sync

import "sync"

type WaitGroup

A WaitGroup waits for a collection of goroutines to finish. The main goroutine calls Add to set the number of goroutines to wait for. Then each of the goroutines runs and calls Done when finished. At the same time, Wait can be used to block until all goroutines have finished.


您向我们提供了一段无法正常工作的代码片段。参见 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)
}

Playground :https://play.golang.org/p/sZmB2Dc5RjL

输出:

map[yes:5 no:5] 1

关于multithreading - 从 goroutine func 发出修改映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49594529/

相关文章:

c - 将字符附加到字符串数组中的字符串时出现段错误

mongodb - 我应该如何使用 mgo 处理 UUID 字段?

go - 测试并发映射读取和映射写入

multithreading - JGroups RPC : NoSuchMethodException

Python - 信号量获取可以从特定线程解锁吗?

c - C中不同类型的指针有什么区别

Golang tmpl HTML 文本被解释为纯文本而不是使用 HTML

java - IBM的JVM还在使用绿色线程?

php - Mysql在每次刷新页面时创建新的线程连接

c++ - 如何将二维数组传递和返回给函数