Lock 与 waitGroup
package share_memory
import (
"sync"
"testing"
"time"
)
func TestCounter(t *testing.T){
counter := 0
for i:=0; i<5000; i++{
go func() {
counter++
}()
}
time.Sleep( 1 * time.Second)
t.Logf("counter = %d",counter)
}
func TestCounterThreadSafe(t *testing.T){
var mut sync.Mutex
counter := 0
for i:=0; i<5000; i++{
go func() {
defer func() {
mut.Unlock()
}()
mut.Lock()
counter++
}()
}
//time.Sleep( 1 * time.Second)
t.Logf("counter = %d",counter)
}
func TestCounterWaitGroup(t *testing.T){
var wg sync.WaitGroup
var mux sync.Mutex
counter := 0
for i:=0; i<5000; i++{
wg.Add(2)
go func() {
defer func() {
mux.Unlock()
}()
mux.Lock()
counter++
wg.Done()
}()
go func() {
defer func() {
mux.Unlock()
}()
mux.Lock()
counter++
wg.Done()
}()
wg.Wait()
}
//time.Sleep( 1 * time.Second)
t.Logf("counter = %d",counter)
}