福哥答案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()
}

执行结果如下:
在这里插入图片描述


评论