- 使用sync.Mutex加锁,解决竟态条件
- 也可以使用管道channel,ch := make(chan bool)
将如下两行注释掉,可复现协程不安全情况
m.Lock()
m.Unlock()
package main
import(
"fmt"
"sync"
"time"
)
var count = 0
func countAdd(wg *sync.WaitGroup, m *sync.Mutex){
m.Lock()
count += 1
m.Unlock()
wg.Done()
// fmt.Printf("count = %d\n", count)
}
func main(){
start := time.Now()
var wg sync.WaitGroup
var m sync.Mutex
for i := 0; i < 10000000; i++ {
wg.Add(1)
go countAdd(&wg, &m)
}
wg.Wait()
// time.Sleep(time.Second*10)
fmt.Printf("count = %d\n", count)
end := time.Now()
usetime := end.Sub(start)
fmt.Printf("use time: %v\n", usetime.Seconds())
}
//`结果`
//`未使用Mutex`
PS D:****\test_Mutex> go run .\main_mutex.go
count = 980
use time: 0.0009954
//`使用Mutex加锁`
PS D:****\test_Mutex> go run .\main_mutex.go
count = 1000
use time: 0.0010021