go 竟态

什么是竟态

当多个routine共享同一资源时就会出现竟态。比如多个routine对同一个全局变量进行+1操作而导致数据操作不准确。
示例:

package main

import (
    "fmt"
    "sync"
)

func main() {
    var count int
    var arithmetic sync.WaitGroup
    Increment := func() {
        count++
    }
    Decrement := func() {
        count--
    }
    for j := 0; j < 100; j++ {
        arithmetic.Add(1)
        go func() {
            defer arithmetic.Done()
            Increment()
        }()
    }
    for i := 0; i < 100; i++ {
        arithmetic.Add(1)
        go func() {
            defer arithmetic.Done()
            Decrement()
        }()
    }
    arithmetic.Wait()
    fmt.Println("count", count)
}

上面这个程序,100个routine并发执行count++;100个routine并发执行count--;最后结果是多少?


执行结果-竟态

上述代码就出现了竟态,两个for循环一共产生200个routine并发操作全局变量count,多个routine读取到同一count的值进行加减操作,最后导致count虽然执行了100次+1和100次-1,但最终结果却不为0

sync.Mutex加锁

我们再来看看下面这个程序

package main

import (
    "fmt"
    "sync"
)

func main() {
    var count int
    var lock sync.Mutex
    var arithmetic sync.WaitGroup
    Increment := func(i int) {
        fmt.Println("Inc", i, "waiting the lock")
        lock.Lock()
        fmt.Println("Inc", i, "lock the lock", count)
        defer lock.Unlock()
        count++
        fmt.Println("Inc", i, "unlock the lock", count)
        fmt.Println()
    }
    Decrement := func(i int) {
        fmt.Println("Dec", i, "waiting the lock")
        lock.Lock()
        fmt.Println("Dec", i, "lock the lock", count)
        defer lock.Unlock()
        count--
        fmt.Println("Dec", i, "unlock the lock", count)
        fmt.Println()
    }
    for j := 0; j < 100; j++ {
        arithmetic.Add(1)
        go func(i int) {
            defer arithmetic.Done()
            Increment(i)
        }(j)
    }
    for i := 0; i < 100; i++ {
        arithmetic.Add(1)
        go func(i int) {
            defer arithmetic.Done()
            Decrement(i)
        }(i)
    }
    arithmetic.Wait() 
    fmt.Println("count", count)
}
执行结果-截取一部分

通过sync.Mutex加锁的方式阻塞routine抢夺同一资源,虽然解决了竟态的问题,但也失去了routine的作用,代码相当于是在顺序执行。

结语

我们在用routine的时候一定要避免竟态的出现,另外网上有很多检测竟态的方法可以用起来。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容