ZhangZhihui's Blog  

Problem: You want to make arrays and slices safe for concurrent use by multiple goroutines.


Solution: Use a mutex from the sync library to safeguard the array or slice. Lock the array or slice before modifying it, and unlock it after modifications are made.

 

Arrays and slices are not safe for concurrent use. If you are going to share a slice or array between goroutines, you need to make it safe from race conditions. Go provides a sync package that can be used for this, in particular, Mutex .

Race conditions occur when a shared resource is used by multiple goroutines trying to access it at the same time:

复制代码
var shared []int = []int{1, 2, 3, 4, 5, 6}

// increase each element by 1
func increase(num int) {
    fmt.Printf("[+%d a]: %v\n", num, shared)
    for i := 0; i < len(shared); i++ {
        time.Sleep(20 * time.Microsecond)
        shared[i] = shared[i] + 1
    }
    fmt.Printf("[+%d b]: %v\n", num, shared)
}

// decrease each element by 1
func decrease(num int) {
    fmt.Printf("[-%d a]: %v\n", num, shared)
    for i := 0; i < len(shared); i++ {
        time.Sleep(10 * time.Microsecond)
        shared[i] = shared[i] - 1
    }
    fmt.Printf("[-%d b]: %v\n", num, shared)
}

func main() {
    for i := 0; i < 5; i++ {
        go increase(i)
    }
    for i := 0; i < 5; i++ {
        go decrease(i)
    }
    time.Sleep(2 * time.Second)
}
复制代码

 

When you run the program, you will see something like this:

复制代码
zzh@ZZHPC:/zdata/MyPrograms/Go/study$ go run main.go
[-4 a]: [1 2 3 4 5 6]
[+4 a]: [1 2 3 4 5 6]
[-0 a]: [1 2 3 4 5 6]
[+3 a]: [1 2 3 4 5 6]
[-1 a]: [1 2 3 4 5 6]
[+0 a]: [1 2 3 4 5 6]
[-2 a]: [1 2 3 4 5 6]
[+2 a]: [2 2 3 4 5 6]
[-3 a]: [1 2 3 4 5 6]
[+1 a]: [0 2 3 4 5 6]
[-4 b]: [1 1 0 1 1 5]
[-0 b]: [1 2 2 1 1 4]
[-2 b]: [1 2 2 0 1 3]
[-1 b]: [1 2 2 0 1 2]
[+4 b]: [1 2 3 3 2 2]
[-3 b]: [1 2 3 3 2 2]
[+0 b]: [1 2 3 3 4 3]
[+2 b]: [1 2 3 4 4 4]
[+3 b]: [1 2 3 4 4 5]
[+1 b]: [1 2 3 4 5 6]
复制代码

How can you prevent such race conditions? Go has the sync package in the standard library that provides you with a mutex , or a mutual exclusion lock:

复制代码
var shared []int = []int{1, 2, 3, 4, 5, 6}
var mutex sync.Mutex

// increase each element by 1
func increaseWithMutex(num int) {
    mutex.Lock()
    fmt.Printf("[+%d a]: %v\n", num, shared)
    for i := 0; i < len(shared); i++ {
        time.Sleep(20 * time.Microsecond)
        shared[i] = shared[i] + 1
    }
    fmt.Printf("[+%d b]: %v\n", num, shared)
    mutex.Unlock()
}

// decrease each element by 1
func decreaseWithMutex(num int) {
    mutex.Lock()
    fmt.Printf("[-%d a]: %v\n", num, shared)
    for i := 0; i < len(shared); i++ {
        time.Sleep(10 * time.Microsecond)
        shared[i] = shared[i] - 1
    }
    fmt.Printf("[-%d b]: %v\n", num, shared)
    mutex.Unlock()
}

func main() {
    for i := 0; i < 5; i++ {
        go increaseWithMutex(i)
    }
    for i := 0; i < 5; i++ {
        go decreaseWithMutex(i)
    }
    time.Sleep(2 * time.Second)
}
复制代码

Using it is quite simple. First you need to declare a mutex. Then, you call Lock on the mutex before you start modifying the shared slice. When you’re done, you call Unlock to unlock the mutex.

 

Here’s the output if you call these functions from main as before:

复制代码
zzh@ZZHPC:/zdata/MyPrograms/Go/study$ go run main.go
[-4 a]: [1 2 3 4 5 6]
[-4 b]: [0 1 2 3 4 5]
[+3 a]: [0 1 2 3 4 5]
[+3 b]: [1 2 3 4 5 6]
[+1 a]: [1 2 3 4 5 6]
[+1 b]: [2 3 4 5 6 7]
[+2 a]: [2 3 4 5 6 7]
[+2 b]: [3 4 5 6 7 8]
[-2 a]: [3 4 5 6 7 8]
[-2 b]: [2 3 4 5 6 7]
[-3 a]: [2 3 4 5 6 7]
[-3 b]: [1 2 3 4 5 6]
[+4 a]: [1 2 3 4 5 6]
[+4 b]: [2 3 4 5 6 7]
[+0 a]: [2 3 4 5 6 7]
[+0 b]: [3 4 5 6 7 8]
[-0 a]: [3 4 5 6 7 8]
[-0 b]: [2 3 4 5 6 7]
[-1 a]: [2 3 4 5 6 7]
[-1 b]: [1 2 3 4 5 6]
复制代码

 

posted on   ZhangZhihuiAAA  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
 
点击右上角即可分享
微信分享提示