线程同步-----读写锁的使用

读写锁;(写独占,读共享; 写锁优先级高)

主要应用函数: (1)pthread_rwlock_init
(2)pthread_rwlock_rdlock
(3)pthread_rwlock_wrlock
(4)pthread_rwlock_tryrdlock
(5)pthread_rwlock_trywrlock
(6)pthread_rwlock_unlock
(7)pthread_rwlock_destory
使用场景:读的次数远大于写的次数时;

代码分析

#include<stdlib.h>
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
pthread_rwlock_t rwlock;
int counter=0;//共享数据,写独占,读共享。

void *pthread_write(void * arg)
{
        int i= (int)arg;
        while(1)
        {       sleep(1);
                pthread_rwlock_wrlock(&rwlock);
                printf("-----write %dtn, counter = %d, tid=%lu\n",i,++counter,pthread_self());
                pthread_rwlock_unlock(&rwlock);
                sleep(3);
        }
}
void *pthread_read(void * arg)
{
        int i = (int)arg;
        while(1)
        {
                sleep(1);
                pthread_rwlock_rdlock(&rwlock);
                printf("-----read %dth, counter = %d,  tid=%lu\n",i,counter,pthread_self());
                pthread_rwlock_unlock(&rwlock);
                sleep(3);
        }
}
int main()
{
        pthread_rwlock_init(&rwlock,NULL);
        pthread_t tid[8];
        int i,ret;

        for(i=0;i<3;++i)
        {
                ret = pthread_create(&tid[i],NULL,pthread_write,(void*)i);
                if(ret != 0)
                        printf("pthread create error\n");
        }
        for(int i=0; i<5;i++)
        {
                ret = pthread_create(&tid[i+3],NULL,pthread_read,(void *)i);
                if(ret != 0)
                        printf("pthread_create error\n");
        }
        for(i=0;i<8;i++)
        {
                pthread_join(tid[i],NULL);
        }
        pthread_rwlock_unlock(&rwlock);
        return 0;
}

发布了52 篇原创文章 · 获赞 14 · 访问量 5605

猜你喜欢

转载自blog.csdn.net/YanWenCheng_/article/details/104085525