Read-Write Lock
同样是保护数据,RW锁比mutex提供更好的并发性,因为RW锁有两三种状态,读锁,写锁,未锁。非常适合保护读多写少的操作需求!
数据结构
pthread_rwlock_t
pthread_rwlockattr_t
读写锁的操作
int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock,const pthread_rwlockattr_t *restrict attr);
int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_timedrdlock(pthread_rwlock_t *restrict rwlock,const struct timespec *restrict tsptr);
int pthread_rwlock_timedwrlock(pthread_rwlock_t *restrict rwlock,const struct timespec *restrict tsptr);
int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);
使用方法和mutx的基本是一样的。
读写锁的属性操作
int pthread_rwlockattr_init(pthread_rwlockattr_t *attr);
int pthread_rwlockattr_destroy(pthread_rwlockattr_t *attr);
int pthread_rwlockattr_getpshared(pthread_rwlockattr_t *restrict attr,const int *restrict pshared);
int pthread_rwlockattr_setpshared(pthread_rwlockattr_t *attr,int pshared);
pshared的值有两个,一个是PTHREAD_PROCESS_PRIVATE,另一个是PTHREAD_PROCESS_SHARED。用法和mutex的一样。