欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

操作系统读者写者问题

程序员文章站 2022-07-04 23:38:19
...
#include <stdio.h>
#include <pthread.h>
#include <windows.h>
#include<process.h>
#include <semaphore.h>
#define N 50
#define wrNum 5 ///写者数目
#define reNum 5 ///读者数目
#define sleepTime  1000

/*
初始化
int sem_init (sem_t *sem, int pshared, unsigned int value);

**:
int sem_post(sem_t *sem);

等待:
int sem_wait(sem_t * sem);
*/



sem_t rmutex ,wmutex;
int readcount=0;

/////////////////////读者//////////////////////////////
void * reader(void *)
{
    while(1)
    {
          sem_wait(&rmutex);         ///p(rmutex)
          if(readcount==0)
          sem_wait(&wmutex);         ///p (wmutex)
          readcount++;
          sem_post(&rmutex);        ///V(rmutex)

           printf("read id%d coming!\n",pthread_self());
        printf("read!%d\n");
        printf("read id%d exit!\n",pthread_self());
        Sleep(sleepTime);
          sem_wait(&rmutex);         ///p (rmutex)
          readcount--;
          if(readcount==0) sem_post(&wmutex);
          sem_post(&rmutex);         ///V(rmutex)
          Sleep(sleepTime);
    }
}
void * writer(void *)
{
    while(1)
    {

        sem_wait(&wmutex);         ///p (wmutex)

        printf("write id%d coming!\n",pthread_self());
        printf("write!\n");
        printf("write id%d exit!\n",pthread_self());
         Sleep(sleepTime);
        sem_post(&wmutex);         ///V(wmutex)
        Sleep(sleepTime);
    }
}
int main()
{
      sem_init(&rmutex,0,1);
      sem_init(&wmutex,0,1);
    pthread_t threadPool[reNum+wrNum];
    int i;
    for(i = 0; i < wrNum; i++)
    {
        pthread_t temp;
        if(pthread_create(&temp, NULL, writer, NULL) == -1)
        {

            exit(1);
        }
        threadPool[i] = temp;
    }///创建写者


    for(i = 0; i < reNum; i++)
    {
        pthread_t temp;
        if(pthread_create(&temp, NULL, reader, NULL) == -1)
        {
            exit(1);
        }
        threadPool[i+wrNum] = temp;
    }///创建读者


    void * result;
    for(i = 0; i < wrNum+reNum; i++)
    {
        if(pthread_join(threadPool[i], &result) == -1)
        {
            exit(1);
        }
    }
    return 0;
}

相关标签: 操作系统