The preceding section describes the synchronization object-mutex in Linux, and the synchronization object-read/write lock in Linux.
If multiple threads read resources at the same time, there will be no competition or resource inconsistency. Therefore, synchronization object protection is not required when reading resources. However, when writing a resource
Otherwise, inconsistency may occur. In the mutex above, no matter whether read or write resources are locked, the efficiency will be relatively low when there are many read resource operations but few write resources. Linux provides
Read/write locks solve the efficiency problem in this case.
Read/write locks are divided into read/write locks. Multiple Threads can simultaneously obtain the read/write locks for their respective read operations. However, the write lock status can only be obtained by one thread. The read lock requests and write lock requests of other threads will be blocked until the current write lock status is released.
Use the following functions to create and destroy read/write locks:
#include <pthread.h> int pthread_rwlock_destroy(pthread_rwlock_t *rwlock); int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock, const pthread_rwlockattr_t *restrict attr);
The read/write lock function is as follows:
#include <pthread.h> int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock); int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);
Pthread_rwlock_rdlock if the current read/write lock is not locked or the read lock status, the function can obtain the read/write lock and return it. If the read/write lock is in the write lock status, the function will block the calling thread, it is released until the write lock status of the read/write lock is released. Pthread_rwlock_tryrdlock if the current read/write lock is not locked or the read lock status, the function can obtain the read/write lock and return it. If the read/write lock is in the write lock status, the function immediately returns an error (the error code is ebusy) without blocking the calling thread.
The function for locking read/write locks is as follows:
#include <pthread.h> int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock); int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
Pthread_rwlock_wrlock: if the current read/write lock status is not locked, the function locks the lock and returns immediately. If the lock status is read or write lock, the function blocks the calling thread until the read/write status of the lock is released. Pthread_rwlock_trywrlock: if the current read/write lock status is unlocked, the function locks the lock and returns immediately. If the lock status is read or write locked, the function immediately returns the error code ebusy without blocking the calling thread.
The function to unlock the read/write lock is as follows:
#include <pthread.h> int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);
Both the Read and Write locks call this function for contact locking.
Original