读者写者模型

读者写者模型

读者与写者之间的关系:
读者与读者:无关系
写者与写者:互斥
读者与写者:互斥

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

读写锁接口:

//1.初始化
int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock,const pthread_rwlockattr_t *restrict attr);

//2.销毁
int pthread_rwlock_destory(pthread_rwlock_t *rwlock);

//3.加锁和解锁
int pthread_rwlock_rdlock(pthread_rwlock_t * rwlock);    //读加锁
int pthread_rwlock_wrlock(pthread_rwlock_t * rwlock);    //写加锁

int pthread_rwlock_unlock(pthread_rwlock_t * rwlock);
#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
#include<stdlib.h>

int counter;
pthread_rwlock_t rwlock;

void* _read(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);
        sleep(1);
    }

}

void* _write(void* arg)
{
    int t;
    int i=*(int*)arg;
    free(arg);

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

        pthread_rwlock_wrlock(&rwlock);
        printf("write:%d :%#x :counter=%d ++counter=%d\n",i,pthread_self(),t,++counter);
        pthread_rwlock_unlock(&rwlock);
        sleep(2);
    }
}

int main()
{
    int i;
    pthread_t tid[8];

    pthread_rwlock_init(&rwlock,NULL);

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

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

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

    pthread_rwlock_destroy(&rwlock);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/lz201788/article/details/80160989