Go   发布时间:2022-04-09  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了即使在golang中使用sync.Mutex也会出现竞争情况大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
完整代码在这里https://play.golang.org/p/ggUoxtcv5m
go run -race main.go说那里有竞争条件我无法解释.
不过,该程序输出了正确的最终结果.

精华:

type SafeCounter struct {
    c int
    sync.Mutex
}

func (c *SafeCounter) Add() {
    c.Lock()
    c.c++
    c.Unlock()
}

var counter *SafeCounter = &SafeCounter{} // global

在增量器中使用* SafeCounter:

func incrementor(s String) {
    for i := 0; i < 20; i++ {
        x := counter
        x.Add()
        counter = x
    }
}

incrementor方法在main中生成两次:

func main() {
    go incrementor()
    go incrementor()
    // some other non-really-related stuff like
    // using waitGroup is ommited here for problem showcase
}

因此,正如我所说,去运行-race main.go将始终说有一个比赛cond发现.

此外,最终的结果总是正确的(至少我已经运行了多次这个程序,它总是说最终计数器是40,这是正确的).
但是,程序在开头打印不正确的值,所以你可以得到类似的东西:

Incrementor1: 0 Counter: 2
Incrementor2: 0 Counter: 3
Incrementor2: 1 Counter: 4
// ang the rest is ok

所以,那里缺少打印1.

有人可以解释为什么有竞争条件我的代码

解决方法

你有很多种族条件,所有比赛都由比赛探测器指出:

x := counter      // this reads the counter value without a lock
    fmt.Println(&x.C)
    x.Add()
    counter = x       // this writes the counter value without a lock
    time.Sleep(time.Duration(rand.Intn(3)) * time.Millisecond)
    fmt.Println(s,i,"Counter:",x.C) // this reads the c field without a lock

> race#1在增量器中读取和写入计数器值之间> race#2是在incrementor中对计数器值的并发写入之间> race#3介于fmt.Println中x.c字段的读取和Add方法中x.c的增量之间.

@H_696_47@

大佬总结

以上是大佬教程为你收集整理的即使在golang中使用sync.Mutex也会出现竞争情况全部内容,希望文章能够帮你解决即使在golang中使用sync.Mutex也会出现竞争情况所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。