[Linux] Understand read-write locks and other locks

Read-write lock

The read-write lock is essentially a spin lock, used to deal with the situation of more reading and less writing.

Behavior of read-write locks

Current lock status Read lock request Write lock request
no lock can can
Read lock can block
Write lock block block

Note :
1. Exclusive resources when writing, sharing resources when reading, write lock priority is higher
2. There is both mutual exclusion and synchronization between writing and reading.
3. The difference between read-write lock and production consumption model: readers will not monopolize the data, nor will it affect the behavior of other readers.

Other locks

Pessimistic lock

Every time you fetch data, you are always worried that the data will be modified by other threads, so you will always lock it before fetching the data. When other threads want to access it, it hangs rather than blocking. Typical: read lock, write lock, row lock

Optimistic lock

Every time data is fetched, it is not considered that the data will be modified by other threads, so it is not locked, but before the data is updated, it is judged whether other data has been modified before the update. There are mainly two methods: version number mechanism and CAS operation.

CAS operation: When the data needs to be updated, determine whether the current memory value is equal to the previously obtained value. If they are equal, update, if not, fail and keep trying.

Spin lock

Keep asking if you can access the data.

Fair/unfair lock

Judging by whether the chance of obtaining the lock is fair

The method of choosing the lock depends on the time to wait for the critical resource:

If the waiting time is long, you can choose to suspend and wait; if the waiting time is short, you can choose the spin lock.

Guess you like

Origin blog.csdn.net/ly_6699/article/details/98470804