gpt4 book ai didi

multithreading - 从 goroutine func 发出修改映射

转载 作者:IT王子 更新时间:2023-10-29 02:02:08 24 4
gpt4 key购买 nike

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/

24 4 0
文章推荐: java - 如何从 JAXBElement 获取对象