• 读写锁


    作用

    互斥锁在任一时刻只允许有一个线程访问关键资源, 不管是读取或写操作.
    读写锁将互斥锁的功能一分为二, 分成读与写两种操作, 当进行读取操作时允许多个线程同时访问, 当进行写操作时只允许一个一个线程访问

    基本函数

    #include <pthread.h>
    int pthread_rwlock_rdlock(pthread_rwlock_t *rwptr);
    int pthread_rwlock_wdlock(pthread_rwlock_t *rwptr);
    int pthread_rwlock_unlock(pthread_rwlock_t *rwptr);
    int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwptr);
    int pthread_rwlock_trywrlock(pthread_rwlock_t *rwptr);
     
    //初始化
    PTHREAD_RWLOCK_INITIALIZER
    int pthread_rwlock_init(pthread_rwlock_t *rwptr,const pthread_rwlockattr_t *attr);
    int pthread_rwlock_destroy(pthread_rwlock_t *rwptr);
    

    例子

    两个线程用读锁读取内容; 两个线程用写锁修改内容

    #include "unpipc.h"
    #include <pthread.h>
     
    struct {
        pthread_rwlock_t rwlock;
        char name[20];
        int age;
    } man = {
        PTHREAD_RWLOCK_INITIALIZER,"aman",20
    };
     
    void *showinfo(void *arg), *changeinfo(void *);
    int main(int argc, char *argv[]){
        pthread_t tid1,tid2;
        pthread_create(&tid1,NULL,showinfo,NULL);
        pthread_create(&tid2,NULL,showinfo,NULL);
     
        pthread_join(tid1,NULL);
        pthread_join(tid2,NULL); 
     
        pthread_create(&tid1,NULL,changeinfo,NULL);
        pthread_create(&tid2,NULL,changeinfo,NULL);
     
        pthread_join(tid1,NULL);
        pthread_join(tid2,NULL);
     
        pthread_rwlock_destroy(&man.rwlock);
        return 0;
    }
     
    void *
    showinfo(void *arg){
        pthread_rwlock_rdlock(&man.rwlock);
        printf("thread %ld: in showinfo
    ",(long)pthread_self());
        printf("name:%s,age:%d
    ",man.name,man.age);
        sleep(3);
        printf("thread %ld: out showinfo
    ",(long)pthread_self());
        pthread_rwlock_unlock(&man.rwlock);
        return NULL;
    }
     
    void *
    changeinfo(void *arg){
        pthread_rwlock_wrlock(&man.rwlock);
        printf("thread %ld: in changeinfo
    ",(long)pthread_self());
        man.age=1;
        printf("name:%s,age:%d
    ",man.name,man.age);
        sleep(3);
        printf("thread %ld: out changeinfo
    ",(long)pthread_self());
        pthread_rwlock_unlock(&man.rwlock);
        return NULL;
    }
    
  • 相关阅读:
    jquery 获取select框选中的值示例一则
    jsp的三种自定义标签 写法示例
    通过 SQL Server 视图访问另一个数据库服务器表的方法
    [转]SQLServer跨服务器访问数据库(openrowset/opendatasource/openquery)
    JS 禁用和重新启用a标签的点击事件
    JS原生父子页面操作
    为什么我们有时不用配置java环境变量?
    Android -- ViewPager多页面滑动切换以及动画效果
    Android -- 程序启动画面 Splash
    apache 伪静态 .htaccess
  • 原文地址:https://www.cnblogs.com/cfans1993/p/5796953.html
Copyright © 2020-2023  润新知