Linux——读写锁

Linux下,为了线程安全,为我们提供了很多种锁。

读写锁: 我们在编写多线程的时候,我们可能需要经常去读取某个共享数据变量,但是相对要改写这个变量的机会相对较少。在读的过程中,往往伴随着查找的操作,中间耗时很长,给这种代码加锁,会极大的降低我们程序的效率。所以提出了读写锁。

这里写图片描述

注意:写独占,读共享,写锁优先级高

例子:4个读线程,4个写线程

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>

pthread_rwlock_t rwlock;        //定义读写锁
int counter;

void *rrout(void *arg)      //读线程函数
{
    int t;
    int i = *(int *)arg;
    free(arg);

    while(1)
    {
        pthread_rwlock_rdlock(&rwlock);

        printf("read:%d   : %#X : counter= %d\n",i,pthread_self(),counter);

        pthread_rwlock_unlock(&rwlock);
        usleep(1111);
    }
}

void *wrout(void *arg)         //写线程函数
{
    int t;
    int i = *(int *)arg;
    free(arg);

    while(1)
    {
        t = counter;
        usleep(1000);

        pthread_rwlock_rdlock(&rwlock);
        printf("write:%d   : %#X : counter= %d, ++counter = %d\n",i,pthread_self(),counter,++counter);
        pthread_rwlock_unlock(&rwlock);
        usleep(11111);
    }
}

int main()
{
    int i = 0 ;
    pthread_t tid[8];
    pthread_rwlock_init(&rwlock,NULL);        //读写锁初始化

    for(i = 0; i < 4; i ++)
    {
        int *p = (int *)malloc(sizeof(int));
        *p = i;
        pthread_create(&tid[i],NULL,rrout,(void *)p);
    }

    for(i = 0; i < 4; i ++)
    {
        int *p = (int *)malloc(sizeof(int));
        *p = i;
        pthread_create(&tid[i + 4],NULL,wrout,(void *)p);
    }

    for(i = 0; i < 8; i++)
    {
        pthread_join(tid[i],NULL);
    }

    pthread_rwlock_destroy(&rwlock);               //销毁读写锁

运行结果:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/Shawei_/article/details/81347399