Different Levels of Write Read Lock

Read write lock is a synchronization technology to solve multi read and write problem. There are three priorities: Read-prefering RW lock, Write-prefering RW lock, and Unspecified priority RW locks.

There are some libraries provide read write lock functions, like:

  • POSIX standard WR lock pthread_rwlock_t (This WR lock provides different priorities)
  • std::shared_mutex in C++17
  • boost::shared_mutex and boost::upgrade_mutex in boost library

The read-copy-update (a.k.a. RCU) is another method to solve mutli reader and write problem. Another solution is seqlock for fewer readers.

A simple persudo implementation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void begin_read() {
lock_r();
counter ++;
if (counter == 1) lock_w();
unlock_r()
void end_read() {
lock_r();
counter --;
if (counter == 0) unlock_w();
unlock_r();
}
void begin_write() {
lock_w();
}
void end_write() {
unlock_w();
}

More details about implementation in C++11 (use atomic variable as spinlock), please see this.

BTH, this simple WR_lock implement method do not gurantee writer has a higher priority.