duanhan8757 2018-10-19 13:31
浏览 39

使用-race标志时,GO中的竞争条件意味着什么

Consider following code:

package main

import (
    "fmt"
    "sync"
)

func main() {
var a int
m := new(sync.Mutex)

wg := sync.WaitGroup{}
wg.Add(2)

go func(){
    m.Lock()
    a = 2
    m.Unlock()
    wg.Done()
}()

go func(){
    //m.Lock()
    a = 9
    //m.Unlock()
    wg.Done()
}()

wg.Wait()

fmt.Println(a)
}

if we run this code with -race flag we get warning that there is a race condition.

1) what can possibly go wrong with this race condition?

if we uncomment lock in second routine we don't get a race condition warning. But we can have different output so a race condition exists.

2) Why now we don't have a race condition warning?

  • 写回答

2条回答 默认 最新

  • dongshaidu2456 2018-10-19 13:40
    关注

    1) what can possibly go wrong with this race condition?

    • Undefined behavior
    • memory corruption
    • crashes Literally the worst possible outcome of not knowing and potentially having a completely invalid value in your variable :p

    2) Why now we don't have a race condition warning?

    Mutex is a primitive which can guarantee atomicity. When lock is uncommented the runtime/os fully syncrhonizes access to the statement(s) that the lock protects. ie a will never be set to both 2 and 9 at the same time.

    There may be a performance implications here (your app may never run into them) because these are serialized operations. This is usually a fine tradeoff because it ensures correctness at the cost of potential performance implications.


    The go documentation has amazing resources around the specifics of this issue:

    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集