讀寫鎖:
讀時(shí)共享,寫時(shí)獨(dú)占酗钞。寫鎖優(yōu)先級(jí)比讀鎖優(yōu)先級(jí)高
package main
import (
"fmt"
"sync"
"time"
)
var mutex sync.Mutex //新建一個(gè)互斥鎖沉桌,默認(rèn)狀態(tài)為0,未加鎖
func printer1(str string){
mutex.Lock() //訪問共享數(shù)據(jù)之前算吩,加鎖
for _,ch := range str {
fmt.Printf("%c",ch)
time.Sleep(time.Millisecond*300)
}
mutex.Unlock()//訪問結(jié)束,解鎖
}
func person11 () {
printer1("Hello")
}
func person22 () {
printer1("World")
}
func main() {
go person11()
go person22()
for {
;
}
}
通過mutex實(shí)現(xiàn)讀時(shí)共享佃扼,寫時(shí)獨(dú)占
代碼示例:
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 {
;
}
}
打印結(jié)果:
thread0寫兼耀,寫入742
########thread742讀压昼,讀出742
########thread742讀,讀出742
thread1寫瘤运,寫入316
########thread316讀窍霞,讀出316
########thread316讀,讀出316
thread0寫拯坟,寫入729
########thread729讀但金,讀出729
########thread729讀,讀出729
通過channel實(shí)現(xiàn)不了讀時(shí)共享郁季,寫時(shí)獨(dú)占
代碼示例:
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 {
;
}
}
打印結(jié)果:
thread3寫,寫入93
########thread4讀似枕,讀出93
thread1寫盖淡,寫入604
thread2寫,寫入78
########thread3讀凿歼,讀出165
thread4寫褪迟,寫入165
########thread1讀,讀出604
########thread0讀答憔,讀出78
thread0寫味赃,寫入769
########thread2讀,讀出769