读写锁:
读时共享,写时独占。写锁优先级比读锁优先级高
package main
import (
"fmt"
"sync"
"time"
)
var mutex sync.Mutex //新建一个互斥锁,默认状态为0,未加锁
func printer1(str string){
mutex.Lock() //访问共享数据之前,加锁
for _,ch := range str {
fmt.Printf("%c",ch)
time.Sleep(time.Millisecond*300)
}
mutex.Unlock()//访问结束,解锁
}
func person11 () {
printer1("Hello")
}
func person22 () {
printer1("World")
}
func main() {
go person11()
go person22()
for {
;
}
}
通过mutex实现读时共享,写时独占
代码示例:
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
var index int
var rwMutxt1 sync.RWMutex
func readRand1(num int) {
for {
rwMutxt1.RLock()
num = index
fmt.Printf("########thread%d读,读出%d\n",num,index)
rwMutxt1.RUnlock()
}
}
func writeRand1(num int) {
for {
randNum := rand.Intn(1000)
rwMutxt1.Lock()
index = randNum
fmt.Printf("thread%d写,写入%d\n",num,randNum)
time.Sleep(time.Microsecond*300)
rwMutxt1.Unlock()
}
}
func main() {
rand.Seed(time.Now().UnixNano())
for i :=0; i < 2; i++ {
go writeRand1(i)
}
for i :=0; i < 2; i++ {
go readRand1(i)
}
//<- quit
for {
;
}
}
打印结果:
thread0写,写入742
########thread742读,读出742
########thread742读,读出742
thread1写,写入316
########thread316读,读出316
########thread316读,读出316
thread0写,写入729
########thread729读,读出729
########thread729读,读出729
通过channel实现不了读时共享,写时独占
代码示例:
package main
import (
"fmt"
"math/rand"
"time"
)
var quit = make(chan bool)
func readRand(in <- chan int,num int) {
for {
rrand := <- in
fmt.Printf("########thread%d读,读出%d\n",num,rrand)
}
}
func writeRand(out chan <- int,num int) {
for {
randNum := rand.Intn(1000)
out <- randNum
fmt.Printf("thread%d写,写入%d\n",num,randNum)
time.Sleep(time.Microsecond*300)
}
}
func main() {
ch := make(chan int)
rand.Seed(time.Now().UnixNano())
for i :=0; i < 5; i++ {
go writeRand(ch,i)
}
for i :=0; i < 5; i++ {
go readRand(ch,i)
}
//<- quit
for {
;
}
}
打印结果:
thread3写,写入93
########thread4读,读出93
thread1写,写入604
thread2写,写入78
########thread3读,读出165
thread4写,写入165
########thread1读,读出604
########thread0读,读出78
thread0写,写入769
########thread2读,读出769