简体   繁体   English

Go语言中潜在的种族条件

[英]potential race condition in go language

I am not sure why the following code has the race condition, can someone give me a hint? 我不确定以下代码为何具有竞争条件,有人可以给我提示吗? I think there is no potential race condition. 我认为没有潜在的比赛条件。 Thank you in advance. 先感谢您。

type PossiblySafeCounter struct {
    mu sync.Mutex
    sum int
}

func (c *PossiblySafeCounter) inc() {
   c.mu.Lock();
   defer c.mu.Unlock();
   go func() {
       c.sum++
   }() 
}
func (c *PossiblySafeCounter) read() int {
    c.mu.Lock();
    defer c.mu.Unlock();
    return c.sum
 }

The c.sum++ is in a goroutine that is scheduled independently of the execution of the inc() method. c.sum++在goroutine中,该c.sum++调度与inc()方法的执行无关。 When the inc() method exits the defer ed unlock of the mutex will happen and will very likely happen at the wrong time, leading to a race condition. inc()方法退出时,互斥体的defer解锁将发生,并且很可能在错误的时间发生,从而导致竞争状态。

As @Flimzy suggests using atomic.AddInt32 would remove the need for a mutex at all. 正如@Flimzy建议使用atomic.AddInt32完全不需要互斥量。

two mutex based solutions are either to not increment in a goroutine: 两个基于互斥量的解决方案要么不在goroutine中递增:

func (c *PossiblySafeCounter) inc() {
   c.mu.Lock();
   defer c.mu.Unlock();
   c.sum++
}

or do the locking and unlocking in the goroutine: goroutine中进行锁定和解锁:

func (c *PossiblySafeCounter) inc() {
   go func() {
       c.mu.Lock();
       defer c.mu.Unlock();
       c.sum++
   }() 
}

but honestly, doing any kind of goroutine doesn't make sense in this example. 但老实说,在此示例中进行任何类型的goroutine都没有意义。 Why do you need the increment to be in a goroutine? 为什么您需要将增量添加到goroutine中?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM