linux系统编程循环创建子线程和读写锁区别

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


int counter;
pthread_rwlock_t rwlock;

void* tfn_write(void*arg)
{
    int i = (int)arg;
    int t;
    while(1)
    {
        pthread_rwlock_wrlock(&rwlock);
        t = counter;
        usleep(1000);
        printf("---------write %d:%lu counter = %d ++counter = %d\n",i+1,pthread_self(),t,++counter);
        pthread_rwlock_unlock(&rwlock);
        usleep(10000);
        
    }
    return NULL;
    
}


void* tfn_read(void*arg)
{
    int i = (int)arg;
    while(1)
    {
        pthread_rwlock_rdlock(&rwlock);
        printf("---------read %d:%lu counter = %d\n",i+1,pthread_self(),counter);
        pthread_rwlock_unlock(&rwlock);
        usleep(2000);
    }
    return NULL;
}

int main(int argc,char* argv[])
{
    int i;
    pthread_t tid[8];
    for(i = 0;i < 3;i++)
    {
        pthread_create(&tid,NULL,tfn_write,(void*)i);
    }  
 
    for(i = 0;i < 5;i++)
    {
        pthread_create(&tid[i+3],NULL,tfn_read,(void*)i);
    }   
    for(i = 0;i < 8;i++)
        pthread_join(tid[i],NULL);
    pthread_rwlock_destroy(&rwlock);
    return 0;
}

读共享,写独占,写锁优先级更高
例如以下运行结果
线程2不可能和线程3一起,因为写锁优先级高,而读锁1和3在他前面
读锁可多线程一起访问如读锁1和3,读锁4 5 2
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值