【Duke】共享内存并发机制 022 - PingPongGooo/GoFoundation GitHub Wiki

共享内存并发机制

package sync 中的
Mutex
RWLock

package share_mem

import (
	"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)
}


打印结果不符合预期。 counter 在不同协程中做。并发。共享了counter

=== RUN   TestCounter
--- PASS: TestCounter (1.00s)
    share_mem_test.go:17: counter = 4803
PASS

改造

package share_mem

import (
	"sync"
	"testing"
	"time"
)

func TestCounter(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 TestCounter(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)
}
=== RUN   TestCounter
--- PASS: TestCounter (0.00s)
    share_mem_test.go:24: counter = 4954
PASS

WaitGroup 同步各个线程的方法

符合预期

func TestCounterWaitGroup(t *testing.T){

	var mut sync.Mutex
	var wg sync.WaitGroup

	counter :=0
	for i:=0; i < 5000; i++{
		wg.Add(1)
		go func(){
			defer func() {
				mut.Unlock()
			}()
			mut.Lock()
			counter ++
			wg.Done()
		}()
	}
	
	wg.Wait()  // 知道 group中的 所有 任务都完成,才往下走。
	t.Logf("counter = %d",counter)
}
=== RUN   TestCounterWaitGroup
--- PASS: TestCounterWaitGroup (0.00s)
    share_mem_test.go:48: counter = 5000
PASS