读写锁sync.RWMutext
实现读者写者问题
package main
import (
"fmt"
"sync"
"time"
)
var rwmutex *sync.RWMutex
var wg *sync.WaitGroup
func main() {
rwmutex = new(sync.RWMutex)
wg = new(sync.WaitGroup)
wg.Add(4)
go readData(1)
go writeData(2)
go readData(3)
go writeData(4)
wg.Wait()
fmt.Println("main...over... ")
}
func writeData(i int) {
defer wg.Done()
fmt.Println(i, "准备写...")
rwmutex.Lock()
fmt.Println(i, "正在写...")
time.Sleep(3 * time.Second)
fmt.Println(i, "写结束(锁内)...")
rwmutex.Unlock()
fmt.Println(i, "写结束...")
}
func readData(i int) {
defer wg.Done()
fmt.Println(i, "准备读...")
rwmutex.RLock()
fmt.Println(i, "正在读取...")
time.Sleep(3 * time.Second)
fmt.Println(i, "读结束(锁内)...")
rwmutex.RUnlock()
fmt.Println(i, "读结束...")
}
网友评论