读写锁的简单说明

#include <pthread.h>

pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;
int pthread_rwlock_init(pthread_rwlock_t *rwlock, const pthread_rwlockattr_t *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_destroy(pthread_rwlock_t *rwlock);

函数原型如上,几点说明如下:

1. 初始化rdlock 可以用 宏,也可以用pthread_rwlock_init()。

2. 上述函数的返回值是0表示成功,非0表示失败。可以strerror(ret) 打印查看失败原因

3. 对读锁或写锁的 unlock 都使用 pthread_rwlock_unlock();

有几次成功的rd_lock之后,必须用unlock几次,否则 pthread_rwlock_destroy() 会返回 EBUSY

4. 加读锁不成功,会产生阻塞;加写锁不成功,会立即返回错误:errno=45,Resource deadlock avoided

如下是一段有错误的测试代码:加读锁之后可以再加读锁,但不能加写锁;加写锁之后,读锁或写锁都不能加了

#include <stdio.h>
#include <string.h>     //for strerror()
#include <pthread.h>

#define RET_CHECK(ret) 
    do{ if(0 != ret) printf("%s
", strerror(ret)); } while(0)

int main()
{
    int ret = -1;
    pthread_rwlock_t rwlock;

    ret = pthread_rwlock_init(&rwlock, NULL);
    printf("init rwlock, ret=%d
", ret);
    RET_CHECK(ret);

    ret = pthread_rwlock_rdlock(&rwlock);
    printf("rdlock sth, ret=%d
", ret);
    RET_CHECK(ret);

    ret = pthread_rwlock_rdlock(&rwlock);
    printf("rdlock sth, ret=%d
", ret);
    RET_CHECK(ret);

    ret = pthread_rwlock_wrlock(&rwlock);
    printf("wrlock sth, ret=%d
", ret);
    RET_CHECK(ret);

    ret = pthread_rwlock_unlock(&rwlock);
    printf("rwlock unlock , ret=%d
", ret);
    RET_CHECK(ret);

    ret = pthread_rwlock_destroy(&rwlock);
    printf("destroy rwlock , ret=%d
", ret);
    RET_CHECK(ret);

    return 0;
}

执行结果如下:

init rwlock, ret=0
rdlock sth, ret=0
rdlock sth, ret=0
wrlock sth, ret=45
Resource deadlock avoided
rwlock unlock , ret=0
destroy rwlock , ret=16
Device or resource busy

原文地址:https://www.cnblogs.com/jyfyonghu/p/11254231.html