写一个读写锁的demo

#include<stdio.h>
#include<unistd.h>
#include<malloc.h>
#include<stdlib.h>
#include<pthread.h>
pthread_rwlock_t rwlock;//声明读写锁
int count;
//写者线程的入口函数
void*route_write(void*arg)
{
    
    
    int i=*(int*)arg;//i是写者线程的编号
    free(arg);
    while(1){
    
    
        int t=count;
        //加锁
        pthread_rwlock_wrlock(&rwlock);
        printf("route_write:%d,%#x,count=%d,++count=%d\n",i,\
                pthread_self(),t,++count);
        //解锁
        pthread_rwlock_unlock(&rwlock);
        sleep(1);
    }
}
//读者线程的入口函数
void*route_read(void*arg)
{
    
    
    int i=*(int*)arg;//i是读者线程的编号
    free(arg);
    while(1){
    
    
        //加锁
        //pthread_rwlock_rdlock(&rwlock);
        pthread_rwlock_rdlock(&rwlock);
        pthread_rwlock_tryrdlock(&rwlock);
        //pthread_rwlock_tryrdlock(&rwlock);
        printf("route_read:%d,%#x,count=%d\n",i,pthread_self(),count);
        //解锁
        pthread_rwlock_unlock(&rwlock);
        sleep(1);
    }
}
int main()
{
    
    
    int i=0;
    //初始化读写锁
    //pthread_rwlock_init(&rwlock,NULL);
    pthread_t tid[8];
    //创建3个写者线程
    for(i=0;i<3;i++){
    
    
        int*p=(int*)malloc(sizeof(int));
        *p=i;
        pthread_create(&tid[i],NULL,route_write,(void*)p);
    }
    //创建3个读者线程
    for(i=0;i<5;i++){
    
    
        int*p=(int*)malloc(sizeof(int));
        *p=i;
        pthread_create(&tid[i+3],NULL,route_read,(void*)p);
    }
    //主线程等待新创建的线程
    for(i=0;i<8;i++)
        pthread_join(tid[i],NULL);
    //销毁读写锁
    pthread_rwlock_destroy(&rwlock);
    return 0;
}

/*gcc rwlock.c -o rwlock -lpthread*/

在这里插入图片描述
总结:目前,读写锁尚且不属于任何的posix标准。

猜你喜欢

转载自blog.csdn.net/qq_38158479/article/details/114987034