乐趣区

关于福大大架构师每日一题:20210220手写代码读写锁

福哥答案 2021-02-20:

四大办法:读加锁,读解锁,写加锁,写解锁。读加锁里有写加锁,读解锁里有写解锁。代码有写线程饥饿景象,但实现简略。

代码用 golang 编写,代码如下:

package main

import (
    "fmt"
    "sync"
    "time"
)

func main() {fdd := FddRWMutex{}
    go func() {
        i := 0
        for k := 0; k < 5; k++ {go func() {
                j := i
                i++
                fdd.RLock()
                fmt.Println("读操作", j)
                time.Sleep(5 * time.Second)
                fdd.RUnlock()}()
            time.Sleep(3 * time.Second)
        }
    }()

    time.Sleep(1000)
    fdd.Lock()
    fmt.Println("写操作 ------------------------------------------")
    fdd.Unlock()
    fmt.Println("有写线程饥饿景象")

}

type FddRWMutex struct {
    w           sync.Mutex
    r           sync.Mutex
    readerCount int
}

func (rw *FddRWMutex) RLock() {rw.r.Lock()
    rw.readerCount++
    if rw.readerCount == 1 {rw.w.Lock()
    }
    rw.r.Unlock()}
func (rw *FddRWMutex) RUnlock() {rw.r.Lock()
    rw.readerCount--
    if rw.readerCount == 0 {rw.w.Unlock()
    }
    rw.r.Unlock()}

func (rw *FddRWMutex) Lock() {rw.w.Lock()
}
func (rw *FddRWMutex) Unlock() {rw.w.Unlock()
}

执行后果如下:


评论

退出移动版