读者-写者

读者写者问题,是指一个写者很多读者,在写者在写文件的时候不允许有读者在读文件,同时有读者读文件时,不允许有写者去写文件。当第一个读者竞争资源和cpu成功后,后面的读者就可以直接读,而写者一直处于等待状态。

sem_init()是对变量初始化

sem_wait() 是对参数进行加1操作

sem_post()是对操作进行减1操作

pthread_create()是创建线程

pthread_join()是以阻塞的方式等待线程结束函数返回时,等待的线程的资源被回收。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <pthread.h>
#include <semaphore.h>
static sem_t mutex_rw;  //写写互斥
static sem_t mutex_r;

static  int count =0 ;
void *read(void *a)
{
    int *p = (int*)a;
    int tid = *p + 1;
    int i;
    for(i=0;i<2;i++)
    {
        sem_wait(&mutex_r);  
        count++;
        printf("count = %d.
",count);
        if(count == 1)    //当第一个读者出现竞争到资源和cpu后,写着处于等待状态
            sem_wait(&mutex_rw);
        sem_post(&mutex_r);
        printf("Reader is ready...
");
        sleep(2);
        printf("Reader finished work!
");
        sem_wait(&mutex_r);
        count--;
        if(count == 0)    //当最后一个读者读完,则告诉写者可以写
            sem_post(&mutex_rw);
        sem_post(&mutex_r);
    }
}
void *write(void *a)
{
    sem_wait(&mutex_rw);
    printf("There are no read ,Writer is ready....
");
    sleep(2);
    printf("Writer finished work!
");
    sem_post(&mutex_rw);
}
int main()
{
    pthread_t read_tid[20];
    pthread_t write_tid[10];
    if(sem_init(&mutex_rw,0,1) == -1 || sem_init(&mutex_r,0,1) == -1)
    {
        printf("init mutex unsuccessfully!
");
        return 0;
    }
    int i;
    for(i=0;i<10;i++)
    {
        pthread_create(&read_tid[i],NULL,read,(void*)&i);
    }
    for(i=0;i<5;i++)
    {
        pthread_create(&write_tid[i],NULL,write,(void*)&i);
    }
    for(i=10;i<20;i++)
    {
        pthread_create(&read_tid[i],NULL,read,(void*)&i);
    }
    for(i=5;i<10;i++)
    {
        pthread_create(&write_tid[i],NULL,write,(void*)&i);
    }
    for(i=0;i<20;i++)
    {
        pthread_join(read_tid[i],NULL);
    }
    for(i=0;i<10;i++)
    {
        pthread_join(write_tid[i],NULL);
    }
    printf("count = %d.
",count);
    return 0;
}
原文地址:https://www.cnblogs.com/chenyang920/p/5387986.html