rwmutex finished

main
Your Name 2024-07-09 00:38:00 +08:00
parent 1b32e6982a
commit 3c356f488a
3 changed files with 54 additions and 1 deletions

View File

@ -2,6 +2,5 @@
<project version="4"> <project version="4">
<component name="VcsDirectoryMappings"> <component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" /> <mapping directory="$PROJECT_DIR$" vcs="Git" />
<mapping directory="$PROJECT_DIR$/logging" vcs="Git" />
</component> </component>
</project> </project>

View File

@ -6,6 +6,7 @@ import (
) )
// 互斥锁 // 互斥锁
// 保证同一时间只有一个goroutine进入临界区其他的goroutine在等待锁的释放多个goroutine等待同一个锁的时候唤醒的策略是随机的
var x = 0 var x = 0
var wg sync.WaitGroup var wg sync.WaitGroup

53
sync/rwmutex.go Normal file
View File

@ -0,0 +1,53 @@
package main
import (
"fmt"
"sync"
"time"
)
// 读写互斥锁,读的时候远远大于写的场景
// rwlock
// 当读的时候加读锁,写的时候加写锁。和互斥锁相比性能差很多
// 当持有写锁所有的goroutine都需要等待写锁解锁不能读也不能写当持有读锁所有goroutine仍然能够读访问共享资源但不允许写
var (
v = 0
locker sync.Mutex
w sync.WaitGroup
rwlocker sync.RWMutex
)
func read() {
defer w.Done()
locker.Lock()
//rwlocker.RLock()
fmt.Println(v)
time.Sleep(time.Millisecond * 1)
locker.Unlock()
//rwlocker.RUnlock()
}
func write() {
defer w.Done()
locker.Lock()
//rwlocker.Lock()
v += 1
time.Sleep(time.Millisecond * 5)
locker.Unlock()
//rwlocker.Unlock()
}
func main() {
start := time.Now()
for i := 0; i < 10; i++ {
w.Add(1)
go write()
}
time.Sleep(time.Second)
for i := 0; i < 1000; i++ {
w.Add(1)
go read()
}
w.Wait()
fmt.Println(time.Now().Sub(start))
}