rwmutex finished
parent
1b32e6982a
commit
3c356f488a
|
@ -2,6 +2,5 @@
|
|||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="$PROJECT_DIR$" vcs="Git" />
|
||||
<mapping directory="$PROJECT_DIR$/logging" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
|
@ -6,6 +6,7 @@ import (
|
|||
)
|
||||
|
||||
// 互斥锁
|
||||
// 保证同一时间只有一个goroutine进入临界区,其他的goroutine在等待锁的释放,多个goroutine等待同一个锁的时候,唤醒的策略是随机的
|
||||
var x = 0
|
||||
|
||||
var wg sync.WaitGroup
|
||||
|
|
|
@ -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))
|
||||
}
|
Loading…
Reference in New Issue