linux 读写锁

读写锁的适用场景:大量读操作,少量写操作;

读并行,读写互斥,写互斥;

在这里插入图片描述

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<pthread.h>
#include<string.h>
pthread_rwlock_t rwlock;
int num=0;
void* write_func(void* arg)
{
        while(num<20000)
        {
                pthread_rwlock_wrlock(&rwlock);
                printf("write:%lu       %d\n",pthread_self(),num++);
                pthread_rwlock_unlock(&rwlock);
                usleep(500);
        }
        pthread_exit(NULL);
}

void* read_func(void* arg)
{
        while(num<20000)
        {
                pthread_rwlock_rdlock(&rwlock);
                printf("read:%lu        %d\n",pthread_self(),num);
                pthread_rwlock_unlock(&rwlock);
                usleep(500);
        }
        pthread_exit(NULL);
}
int main()
{
        int i=0;
        pthread_t pthread_id[8]={0};
        /*线程分离*/
/*      pthread_attr_t attr;
        pthread_attr_init(&attr);
        pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);*/
         /*初始化读写锁*/
        pthread_rwlock_init(&rwlock,NULL);
        /*创建三个写线程*/
        for(;i<3;i++)
        {
                strerror(pthread_create(&pthread_id[i],NULL,write_func,NULL));
        }
        /*创建五个读线程*/
        for(i=3;i<8;i++)
        {
                strerror(pthread_create(&pthread_id[i],NULL,read_func,NULL));
        }
        /*销毁线程分离属性*/
        //pthread_attr_destroy(&attr);
        /*销毁读写锁*/
        for(i=0;i<8;i++)
        {
                pthread_join(pthread_id[i],NULL);
                printf("thread %d has finished!\n",i);
        }
        pthread_rwlock_destroy(&rwlock);
        return 0;
}
                                           

注意:在销毁读写锁或者互斥锁之前一定要保证所有子线程已经退出。在子线程还没退出前销毁读写锁或者互斥锁会导致子线程终止;

还有,设置线程分离之后不能再用pthread_join()回收子线程,否则会造成程序崩溃;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值