This is a creation in Article, where the information may have evolved or changed.
About sync. Rwmutex
About the priority level
- In order to emulate barrier in Pthread, the Rwmutex mate blocking pipeline is used in the code. One of the key issues is the priority of read and write locks.
- In the document there is this sentence: a blocked lock call excludes new readers from acquiring the lock.
So we can see that a blocked write lock prevents the new reader from requesting a read lock.
- To summarize, we can put the program in stages to illustrate this behavior.
- N readers add n read locks
- A writer tries to add a write lock that is blocked
- Subsequent readers cannot successfully acquire a read lock.
- Unlock all n Read locks
- Write lock is awakened, write operation is completed, write lock is unlocked
- Subsequent readers are awakened, read locks are received, and read operations are completed
- Test code:
package mainimport "fmt"import "time"import "sync"func main() { var wg sync.WaitGroup var rw sync.RWMutex wg.Add(3) go func() { defer wg.Done() rw.RLock() time.Sleep(3 * time.Second) rw.RUnlock() }() go func() { defer wg.Done() time.Sleep(1 * time.Second) rw.Lock() fmt.Println("Get Write Lock") rw.Unlock() }() go func() { defer wg.Done() time.Sleep(2 * time.Second) rw.RLock() fmt.Println("Get Read Lock") rw.RUnlock() }() wg.Wait()}输出: Get Write Lock Get Read Lock
Wake-up problem for locks
- What happens when the lock is lifted. Continue to execute goroutine or wake up waiting locks?
- Test code:
package mainimport "fmt"import "time"import "sync"func main() { var wg sync.WaitGroup var fuck sync.RWMutex wg.Add(2) go func() { time.Sleep(20 * time.Millisecond) for i := 0; i < 1000; i++ { fuck.Lock() fmt.Printf("Write lock %d\n",i) fuck.Unlock() } wg.Done() }() go func() { time.Sleep(18 * time.Millisecond) for i := 0; i < 1000; i++ { fuck.RLock() fmt.Printf("Read lock %d\n",i) fuck.RUnlock() } wg.Done() }() wg.Wait()}输出: N * Read lock Write lock Read lock Write lock Read lock Write lock Read lock .... N * Write lock
- Conclusion after unlocking, go will wake up the waiting lock instead of continuing to execute
- It seems that sleep will be awakened (to be solved)