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;
    }
    
  • 相关阅读:
    5种主要聚类算法的简单介绍-转发
    序列标注中的BIO标注介绍
    Lecture1- Introduction and Word Vectors 斯坦福 nlp 教程
    Word embedding
    RNN
    《生成对抗网络GAN的原理与应用专题》笔记
    《自控力》《基因组:人类自传》的读后联想
    开源共享一个训练好的中文词向量(语料是维基百科的内容,大概1G多一点)
    “程序的迭代”——复杂性度量随想
    人工智能算法脑图
  • 原文地址:https://www.cnblogs.com/cfans1993/p/5796953.html
Copyright © 2011-2022 走看看