错误代码,结构体是值传递,将mutex传进去,体现不了效果。
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
var count int
var mutex sync.RWMutex
func write(n int, mutex sync.RWMutex) {
time.Sleep(2 * time.Second)
rand.Seed(time.Now().UnixNano())
fmt.Printf("读 goroutine %d 准备写锁...\n", n)
mutex.Lock()
fmt.Printf("写 goroutine %d 正在写数据...\n", n)
time.Sleep(5*time.Second)
num := rand.Intn(500)
count = num
fmt.Printf("写 goroutine %d 写数据结束,写入新值 %d\n", n, num)
time.Sleep(3 * time.Second)
mutex.Unlock()
}
func read(n int, mutex sync.RWMutex) {
fmt.Printf("读 goroutine %d 准备读锁...\n", n)
mutex.RLock()
fmt.Printf("读 goroutine %d 正在读取数据...\n", n)
time.Sleep(20 * time.Second)
num := count
fmt.Printf("读 goroutine %d 读取数据结束,读到 %d\n", n, num)
mutex.RUnlock()
time.Sleep(5 * time.Second)
}
func main() {
var mutex sync.RWMutex
for i := 0; i < 1; i++ {
go read(i + 1, mutex)
}
for i := 0; i < 1; i++ {
go write(i + 1, mutex)
}
time.Sleep(time.Second * 35)
}