#include <stdio.h>
#include <pthread.h>
#include <windows.h>
#include<process.h>
#include <semaphore.h>
#define N 50
#define proNum 10 ///生产者数量
#define conNum 5 ///消费者数量
#define sleepTime 5
/*
初始化
int sem_init (sem_t *sem, int pshared, unsigned int value);
激活:
int sem_post(sem_t *sem);
等待:
int sem_wait(sem_t * sem);
*/
int buffer[N] = {0};
int in = 0;
int out = 0;
int id = 0;
sem_t mutex , empty ,full;
/////////////////////生产者//////////////////////////////
void *producer(void * )
{
while(1)
{
sem_wait(&empty); ///p(wait)
sem_wait(&mutex); ///p (mutex)
id++; ///确定id
printf("productID%d,position%d\n",id,in);
buffer[in] = id;
in = (in + 1) % N;
sem_post(&mutex); ///V(mutex)
sem_post(&full); ///V(full)
Sleep(sleepTime);
}
}
void *consumer( void *)
{
while(1)
{
sem_wait(&full); ///p(full)
sem_wait(&mutex); ///p (mutex)
int nextc = buffer[out];
buffer[out] = 0;
out = (out + 1) % N;
sem_post(&mutex); ///V(mutex)
sem_post(&empty); ///V(empty)
printf("consumeID%d,position%d\n", nextc,out);
Sleep(sleepTime);
}
}
int main()
{
sem_init(&mutex,0,1);
sem_init(&empty,0,N);
sem_init(&full,0,1);
pthread_t threadPool[proNum+conNum];
int i;
for(i = 0; i < proNum; i++)
{
pthread_t temp;
if(pthread_create(&temp, NULL, producer, NULL) == -1)
{
exit(1);
}
threadPool[i] = temp;
}///创建生产者
for(i = 0; i < conNum; i++)
{
pthread_t temp;
if(pthread_create(&temp, NULL, consumer, NULL) == -1)
{
exit(1);
}
threadPool[i+proNum] = temp;
}///创建消费者
void * result;
for(i = 0; i < proNum+conNum; i++)
{
if(pthread_join(threadPool[i], &result) == -1)
{
exit(1);
}
}
return 0;
}
操作系统生产者消费者
猜你喜欢
转载自blog.csdn.net/zzyzzylalala/article/details/104047925
今日推荐
周排行