Linux_线程同步_读写锁

读写锁(共享_独占锁)pthread_rwlock_t

特性:写独占,读共享。(写锁优先级高)

读写锁只有一把,但其具备两种状态:

  1. 读模式下加锁状态 (读锁)
  2. 写模式下加锁状态 (写锁)

读写锁是“写模式加锁”时, 解锁前,所有对该锁加锁的线程都会被阻塞。

读写锁是“读模式加锁”时, 如果线程以读模式对其加锁会成功;如果线程以写模式加锁会阻塞。

读写锁是“读模式加锁”时, 既有试图以写模式加锁的线程,也有试图以读模式加锁的线程。那么读写锁会阻塞随后的读模式锁请求。优先满足写模式锁。读锁、写锁并行阻塞,写锁优先级高。

读写锁适合于对数据结构读的次数远大于写的情况。

初始化:

int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock, const pthread_rwlockattr_t *restrict attr);
attr表读写锁属性,通常使用默认属性,传NULL即可。
同样可使用PTHREAD_RWLOCK_INITIALIZER初始化。

销毁:

int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);

读方式加锁:

int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock); //非阻塞

写方式加锁:

int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock); //非阻塞

解锁:

int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
 
int counter;
pthread_rwlock_t rwlock;  //定义 全局 读写锁
 
/* 3个线程不定时写同一全局资源,5个线程不定时读同一全局资源 */
void *th_write(void *arg)
{
    int t, i = (int)arg;
    while (1) {
        pthread_rwlock_wrlock(&rwlock); //加写锁,独占
        t = counter; 
        usleep(1000); //锁 还在自己手上
        printf("=======write %d: %lu: counter=%d ++counter=%d\n", i, pthread_self(), t, ++counter);
        pthread_rwlock_unlock(&rwlock); //解锁
        usleep(10000);
    }
    return NULL;
}
 
void *th_read(void *arg)
{
    int i = (int)arg;
 
    while (1) {
        pthread_rwlock_rdlock(&rwlock); //加读锁,共享
        printf("----------------------------read %d: %lu: %d\n", i, pthread_self(), counter);
        pthread_rwlock_unlock(&rwlock);
        usleep(2000); //让写线程有机会获得CPU
    }
    return NULL;
}
 
int main(void)
{
    int i;
    pthread_t tid[8];  //记录各个线程ID 便于后续 pthread_join
 
    pthread_rwlock_init(&rwlock, NULL); //初始化读写锁   自己写代码要加返回值检查
 
    for (i = 0; i < 3; i++)
        pthread_create(&tid[i], NULL, th_write, (void *)i);
 
    for (i = 0; i < 5; i++)
        pthread_create(&tid[i+3], NULL, th_read, (void *)i);
 
    for (i = 0; i < 8; i++)
        pthread_join(tid[i], NULL);
 
    pthread_rwlock_destroy(&rwlock); //销毁读写锁
 
    return 0;
}			
  • 7
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值