• 读写锁的简单说明


    #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

  • 相关阅读:
    解决SharePoint 文档库itemadded eventhandler导致的上传完成后,编辑页面保持报错的问题,错误信息为“该文档已经被编辑过 the file has been modified by...”
    解决SharePoint 2013 designer workflow 在发布的报错“负载平衡没有设置”The workflow files were saved but cannot be run.
    随机实例,随机值
    Spring4笔记
    struts2笔记(3)
    struts2笔记(2)
    获取文本的编码类型(from logparse)
    FileUtil(from logparser)
    DateUtil(SimpleDateFormat)
    struts2笔记
  • 原文地址:https://www.cnblogs.com/jyfyonghu/p/11254231.html
Copyright © 2020-2023  润新知