读写锁

在有一种情况下,某些应用数据中读数据比修改数据频繁,这时候我们可以考虑使用读写锁机制。

读写锁的规则:

只要没有线程在修改某个给定的数据,那么任意数目的线程都可以拥有该数据的读访问权限。

仅当没有其他线程在读在改某个给定的数据时,当前进程才可以修改它。

如同互斥锁和条件变量一样,都可以静态和动态初始化,并且修改属性,从而达到线程间和进程间的同步。

       #include <pthread.h>

       int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
       int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);
       int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock);
       int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
       int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);

       #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);
PTHREAD_RWLOCK_INITIALIZER

 

       #include <pthread.h>

       int     pthread_rwlockattr_destroy(pthread_rwlockattr_t
       *attr);
       int        pthread_rwlockattr_init(pthread_rwlockattr_t
       *attr);

       #include <pthread.h>

       int pthread_rwlockattr_getpshared(const pthread_rwlock‐
       attr_t *
              restrict attr, int *restrict pshared);
       int  pthread_rwlockattr_setpshared(pthread_rwlockattr_t
       *attr,
              int pshared);

 

 

 

 

 

你可能感兴趣的:(读写锁)