Golang以其并发性Goroutines
而闻名。不仅是并发,还有更多。
因此,在这种情况下,我们必须确保多个goroutines
不应该同时试图修改资源,从而导致冲突。
为了确保资源一次只能被一个goroutine
访问,我们可以使用一个叫做sync.Mutex
的东西。
This concept is called mutual exclusion, and the conventional name for the data structure that provides it is mutex. — Go dev
无Mutex的用例
让我们有一个简单的用例来理解Mutex
在goroutines
中的使用。
例如,如果我们需要通过一个goroutine
增加一个变量的值,并通过另一个goroutine
减少同一个变量的值。
package main
import (
"fmt"
"sync"
"time"
)
func main() {
const loop = 100
var wg sync.WaitGroup
wg.Add(loop * 2)
// declaring a shared value
var n int = 0
for i := 0; i < loop; i++ {
go func() {
time.Sleep(time.Second / 10)
n++
wg.Done()
}()
go func() {
time.