read_lock和write_lock的优点

The advantages of read_lock and write_lock

我正在学习 read_lock 和 write_lock。

好像可以用spin_lock代替读写锁

所以我想知道使用读写锁有什么好处

当我使用 read_lock 和 write_lock 时,与仅使用 spin_lock 相比有什么优势?

简短的谷歌搜索将这一段翻了过来:

Sometimes, lock usage can be clearly divided into readers and writers. For example, consider a list that is both updated and searched. When the list is updated (written to), it is important that no other threads of execution concurrently write to or read from the list. Writing demands mutual exclusion. On the other hand, when the list is searched (read from), it is only important that nothing else write to the list. Multiple concurrent readers are safe so long as there are no writers. The task list's access patterns (discussed in Chapter 3, "Process Management") fit this description. Not surprisingly, the task list is protected by a reader-writer spin lock.

(来源:link

所以基本上,使用 read_lock/write_lock 比 deny/allow 不同锁用户的常规自旋锁更强大,这取决于他们的需要,如上例所示。

Read-Write锁在架构明确划分为reader和writers,读次数较多的场景下比较有用。即读写锁允许多个reader在同一个临界区。然而,普通自旋锁无法在具有更多读取的场景中以并行处理的形式提供此优势。