Go语言学习笔记-并发编程-共享内存并发机制

Mutex

WaitGroup

类似java中的join

package share_mem
import (
        "sync"
        "testing"
        "time"
)

func TestCounter(t *testing.T) {
        counter := 0
        for i := 0; i < 1000; i++ {
                go func() {

                        counter++
                }()

        }
        time.Sleep(2 * time.Second)
        t.Logf("counter = %d",counter)

}

func TestCounterSafe(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 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()
                }()
        }
        //time.Sleep(1 * time.Second)
        wg.Wait()
        t.Logf("counter = %d", counter)

}

你可能感兴趣的:(Go语言学习笔记-并发编程-共享内存并发机制)