读写互斥锁(RWMutex):读写互斥锁是互斥锁的一种扩展,可以实现多个goroutine同时读取共享变量,但只允许一个goroutine进行写入。通过使用读写互斥锁,可以在读多写少的场景中提高并发性能。例如:
package main
import (
	"fmt"
	"sync"
)
var (
	count int
	mutex sync.RWMutex
)
func readCount() {
	mutex.RLock()
	defer mutex.RUnlock()
	fmt.Println("Count:", count)
}
func increment() {
	mutex.Lock()
	defer mutex.Unlock()
	count++
}
func main() {
	var wg sync.WaitGroup
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			readCount()
		}()
	}
	for i := 0; i < 5; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			increment()
		}()
	}
	wg.Wait()
}
countmutexreadCountRLock()countincrementLock()count