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;
    }
    
  • 相关阅读:
    rpm 命令|rpm 安装|rpm 卸载|rpm 使用|rpm 删除
    Linux中如何开启8080端口供外界访问 和开启允许对外访问的端口8000
    git远程提交到github或者gitee
    git搭建私有仓库
    Linux命令行设置环境变量
    【Little_things】控制台五子棋(java)
    【cisco实验】练习 2.3.8: 配置基本交换机管理
    操作系统FCFS,SJF进程调度(C++)
    JavaBean的编译和部署说明
    【Python爬虫】爬取个人博客的图片
  • 原文地址:https://www.cnblogs.com/cfans1993/p/5796953.html
Copyright © 2011-2022 走看看