zoukankan      html  css  js  c++  java
  • 读写锁

    作用

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

    基本函数

    #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;
    }
    
  • 相关阅读:
    MySQL的排序方式
    Hibernate中查询优化策略
    kafka实现SASL_PLAINTEXT权限认证·集成springboot篇
    kafka实现SASL_PLAINTEXT权限认证·服务器篇
    SpringMvc服务端实现跨域请求解决方案
    maven打包日志输出优化-去掉泛型与过时的警告
    SpringMVC之控制器的单例和多例管理
    springmvc中的controller是单例的
    com.caucho.hessian.io.HessianProtocolException: is unknown code 解决方案
    浅谈大型web系统架构
  • 原文地址:https://www.cnblogs.com/cfans1993/p/5796953.html
Copyright © 2011-2022 走看看