小编auj*_*jau的帖子

X 个 goroutine 更新相同的变量

我想让 X 个 goroutineCountValue使用并行性进行更新(numRoutines 与你拥有的 CPU 数量一样多)。

解决方案一:

func count(numRoutines int) (countValue int) {
    var mu sync.Mutex
    k := func(i int) {
        mu.Lock()
        defer mu.Unlock()
        countValue += 5
    }
    for i := 0; i < numRoutines; i++ {
        go k(i)
    }
Run Code Online (Sandbox Code Playgroud)

它变成了数据竞争和返回的countValue = 0.

解决方案2:

func count(numRoutines int) (countValue int) {
    k := func(i int, c chan int) {
        c <- 5
    }
    c := make(chan int)
    for i := 0; i < numRoutines; i++ { …
Run Code Online (Sandbox Code Playgroud)

concurrency go race-condition

3
推荐指数
1
解决办法
1913
查看次数

标签 统计

concurrency ×1

go ×1

race-condition ×1