go 笔记 十四章 并发编程 sync 包的使用和示例

互斥锁 sync.Mutex{}

package main

import (
	"fmt"
	"sync"
	"time"
)

func main() {
	lock := &sync.Mutex{}
	go lockFunc(lock)
	go lockFunc(lock)
	go lockFunc(lock)
	go lockFunc(lock)
	for {
	}
}

func lockFunc(lock *sync.Mutex) {
	lock.Lock()
	fmt.Println("lockFunc once per second")
	time.Sleep(1 * time.Second)
	lock.Unlock()
}

读锁 sync.RWMutex{}
在读取的时候,不会阻塞其他读取,但是会阻塞写入

写锁 写的时候,会阻塞其他读取和写入

package main

import (
	"fmt"
	"sync"
	"time"
)

func main() {
	lock := &sync.RWMutex{}
	go writeFunc(lock)
	go writeFunc(lock)
	go readFunc(lock)
	go readFunc(lock)
	go readFunc(lock)
	go readFunc(lock)
	go readFunc(lock)

	for {
	}
}

func writeFunc(lock *sync.RWMutex) {
	lock.Lock()
	fmt.Println("write once per second")
	time.Sleep(1 * time.Second)
	lock.Unlock()
}

func readFunc(lock *sync.RWMutex) {
	lock.RLock()
	fmt.Println("read once per second")
	time.Sleep(1 * time.Second)
	lock.RUnlock()
}
/*
write once per second
read once per second
read once per second
read once per second
read once per second
read once per second
write once per second

*/

once once := &sync.Once{}
once.Do(func() { // 只执行一次
fmt.Println(“once”)
})

package main

import (
	"fmt"
	"sync"
)

func main() {
	once := &sync.Once{}

	for i := 0; i < 10; i++ {
		once.Do(func() {
			fmt.Println(i)
		})
	}

}

sync.WaitGroup{}

package main

import (
	"sync"
	"time"
)

func main() {
	wg := &sync.WaitGroup{}
	wg.Add(2)
	go func() {
		time.Sleep(2 * time.Second)
		println("sleep 2 second")
		wg.Done()
	}()

	go func() {
		time.Sleep(1 * time.Second)
		println("sleep 1 second")
		wg.Done()
	}()

	wg.Wait()
}

sync.Map{} 可以进行并发读、写、删除

package main

import (
	"fmt"
	"sync"
	"time"
)

func main() {
	m := &sync.Map{}

	go func() {
		for {
			m.Store("1", "a")
		}
	}()

	go func() {
		for {
			fmt.Println(m.Load("1"))
		}
	}()
	time.Sleep(100)
}

sync.Pool{} 并发池

package main

import (
	"fmt"
	"sync"
	"time"
)

func main() {
	p := sync.Pool{}
	p.Put(1)
	p.Put(2)
	p.Put(3)
	p.Put(4)
	for i := 0; i < 7; i++ {
		time.Sleep(1 * time.Second)
		result := p.Get()
		fmt.Println(result)
	}
}

sync.Cond{} 条件变量

package main

import (
	"fmt"
	"sync"
	"time"
)

func main() {
	cond := sync.NewCond(&sync.Mutex{})
	go func() {
		cond.L.Lock()
		fmt.Println("lock 1")
		cond.Wait()
		fmt.Println("un lock 1")
		cond.L.Unlock()
	}()

	go func() {
		cond.L.Lock()
		fmt.Println("lock 2")
		cond.Wait()
		fmt.Println("un lock 2")
		cond.L.Unlock()
	}()

	time.Sleep(1 * time.Second)
	cond.Broadcast()
	time.Sleep(1 * time.Second)
}

你可能感兴趣的:(笔记,go,golang,笔记,c++)