github.com/nibnait/go-learn@v0.0.0-20220227013611-dfa47ea6d2da/src/test/chapter/ch4/25_share_mem_test.go (about) 1 package ch4 2 3 import ( 4 "sync" 5 "testing" 6 "time" 7 ) 8 9 func TestCounter(t *testing.T) { 10 11 counter := 0 12 for i := 0; i < 5000; i++ { 13 go func() { 14 counter++ 15 }() 16 } 17 time.Sleep(1 * time.Second) 18 t.Logf("counter = %d", counter) 19 20 } 21 22 // lock unlock --> sync.Mutex 23 func TestCounterThreadSafeMutex(t *testing.T) { 24 var mut sync.Mutex 25 counter := 0 26 for i := 0; i < 5000; i++ { 27 go func() { 28 defer func() { 29 mut.Unlock() 30 }() 31 32 mut.Lock() 33 counter++ 34 }() 35 } 36 time.Sleep(1 * time.Second) 37 t.Logf("counter = %d", counter) 38 } 39 40 // lock unlock --> sync.RWLock ✅ 读多写少时,性能更好 41 func TestCounterThreadSafeRWLock(t *testing.T) { 42 var rwMutex sync.RWMutex 43 counter := 0 44 for i := 0; i < 5000; i++ { 45 go func() { 46 defer func() { 47 rwMutex.Unlock() 48 }() 49 50 rwMutex.Lock() 51 counter++ 52 }() 53 } 54 time.Sleep(1 * time.Second) 55 t.Logf("counter = %d", counter) 56 } 57 58 // thread.join -> sync.WaitGroup(.Add(1), .Done, .Wait) 59 func TestCounterWaitGroup(t *testing.T) { 60 var mut sync.Mutex 61 var wg sync.WaitGroup 62 counter := 0 63 for i := 0; i < 5000; i++ { 64 wg.Add(1) 65 go func() { 66 defer func() { 67 mut.Unlock() 68 }() 69 70 mut.Lock() 71 counter++ 72 73 wg.Done() 74 }() 75 } 76 77 wg.Wait() 78 t.Logf("counter = %d", counter) 79 }