共享内存并发机制
Lock
错误示范
package share_test
import (
"testing"
"time"
)
func TestCounter(t *testing.T) {
coun := 0
for i := 0; i < 5000; i++ {
go func() {
coun++
}()
}
time.Sleep(time.Second)
t.Log(coun)
}
在不同的协程中进行自增,增加了相互竞争。不是一个线程安全的程序
正确写法
func TestCounterThreadSafe(t *testing.T) {
var mut sync.Mutex
coun := 0
for i := 0; i < 5000; i++ {
go func() {
defer func() {
mut.Unlock()
}()
mut.Lock()
coun++
}()
}
time.Sleep(time.Second)
t.Log(coun)
}
WaitGroup
func TestCounterWaitGroup(t *testing.T) {
var wg sync.WaitGroup
var mut sync.Mutex
coun := 0
for i := 0; i < 5000; i++ {
wg.Add(1)
go func() {
mut.Lock()
defer func() {
mut.Unlock()
}()
coun++
wg.Done()
}()
}
wg.Wait()
t.Log(coun)
}
精确控制等待时间