Linux thread synchronization read-write lock rwlock


Read-write locks have higher applicability than mutex. Multiple threads can occupy read-write locks in read mode at the same time, but only one thread can occupy read-write locks in write mode.
1. When the read-write lock is in the write-locked state, before the lock is unlocked, all threads that attempt to lock the lock will be blocked;
2. When the read-write lock is in the read-locked state, all attempts to use the read mode The thread that locks it can get access, but the thread that locks it in write mode will block;
3. When the read-write lock is in the read mode lock state, if another thread tries to lock it in write mode, the read Write locks usually block subsequent read mode lock requests, which can avoid long-term occupancy of read mode locks, and long-term blocking of waiting write mode lock requests;
this kind of lock is suitable for reading the data structure more frequently than writing. , because read lock sharing is possible.

API interface description:
1) Initialization and destruction

#include <pthread.h>
int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock, const pthread_rwlockattr_t *restrict attr);
int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);

Returns 0 if successful, and returns an error number if there is an error.
2) The two functions of read lock and write lock
to acquire locks are blocking operations

#include <pthread.h>
int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);

Returns 0 if it is successful, and returns the error number if there is an error.
3) Non-blocking acquisition of read locks and write locks
Non-blocking lock acquisition operations, if it can be acquired, it will return 0, otherwise it will return an error EBUSY.

#include <pthread.h>
int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock);

Returns 0 if successful, and returns the error number if there is an error.


From: http://www.cnblogs.com/caosiyang/archive/2011/11/25/2262980.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326490313&siteId=291194637