生产者消费者问题:
编写生产者消费者函数:
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include <time.h>
#define NUM_OF_PRODUCER 5 // 生产者的数目
#define NUM_OF_CONSUMER 4
#define M 3 // 缓冲数目
#define NUM_OF_PRODUCTION 15
int in = 0; // 生产者放置产品的位置
int out = 0; // 消费者取产品的位置
int buff[M] = {0}; // 缓冲初始化为0, 开始时没有产品
sem_t empty_sem; // 同步信号量, 当满了时阻止生产者放产品
sem_t full_sem; // 同步信号量, 当没产品时阻止消费者消费
pthread_mutex_t mutex; // 互斥信号量, 一次只有一个线程访问缓冲
int product_id = 0; //生产者id
int consumer_id = 0; //消费者id
int count = 0; //生产商品数
/* 打印缓冲情况 */
void print()
{
int i;
printf("time:%lu 缓存区状态:\n",clock());
for(i = 0; i < M; i++)
printf("%d ", buff[i]);
printf("\n");
}
/* 生产者方法 */
void *product()
{
int id = ++product_id;
while(count < = NUM_OF_PRODUCTION)
{
// 用sleep的数量可以调节生产和消费的速度,便于观察
sleep(1);
//sleep(1);
sem_wait(&empty_sem);
pthread_mutex_lock(&mutex);
in = in % M;
printf("%time:product%d in %d. like: \t",clock(), id, in);
buff[in] = 1;
print();
++in;
count ++;
pthread_mutex_unlock(&mutex);
sem_post(&full_sem);
}
}
/* 消费者方法 */
void *consumer()
{
int id = ++consumer_id;
while(1)
{
// 用sleep的数量可以调节生产和消费的速度,便于观察
sleep(1);
//sleep(1);
sem_wait(&full_sem);
pthread_mutex_lock(&mutex);
out = out % M;
printf("time:%lu consumer:%d in %d. like: \t",clock(), id, out);
buff[out] = 0;
print();
++out;
pthread_mutex_unlock(&mutex);
sem_post(&empty_sem);
}
}
int main()
{
pthread_t id1[NUM_OF_PRODUCER];
pthread_t id2[NUM_OF_CONSUMER];
int i;
int pro[NUM_OF_PRODUCER];
int cos[NUM_OF_CONSUMER];
// 初始化同步信号量
int ini1 = sem_init(&empty_sem, 0, M);
int ini2 = sem_init(&full_sem, 0, 0);
if(ini1 && ini2 != 0)
{
printf("time:%d sem init failed \n",clock());
exit(1);
}
//初始化互斥信号量
int ini3 = pthread_mutex_init(&mutex, NULL);
if(ini3 != 0)
{
printf("time:%d mutex init failed \n",clock());
exit(1);
}
// 创建N个生产者线程
for(i = 0; i < NUM_OF_PRODUCER; i++)
{
pro[i] = pthread_create(&id1[i], NULL, product, (void *)(&i));
if(pro[i] != 0)
{
printf("time:%d product%d creation failed \n",clock(), i);
exit(1);
}
}
//创建N个消费者线程
for(i = 0; i < NUM_OF_CONSUMER; i++)
{
cos[i] = pthread_create(&id2[i], NULL, consumer, NULL);
if(cos[i] != 0)
{
printf("time:%lu consumer%d creation failed \n",clock(), i);
exit(1);
}
}
//销毁线程
for(i = 0; i < NUM_OF_CONSUMER; i++)
{
pthread_join(id2[i],NULL);
}
for(i = 0; i < NUM_OF_PRODUCER; i++)
{
pthread_join(id1[i],NULL);
}
exit(0);
}
gcc -o test test.c -lpthread