#include <semaphore.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <time.h>
struct data
{
sem_t empty;
sem_t full;
char buf[32];
};
struct data msg;
//生产者工作
void *produce(void *v)
{
char *buf[] = {"苹果", "梨", "香蕉", "榴莲", "橙子", "西瓜", "芒果", "火龙果"};
while(1)
{
sem_wait(&msg.empty);
strcpy(msg.buf, buf[rand()%8]);
printf("生产了一个%s\n", msg.buf);
int time = rand() % 100 + 1;
usleep(time*10000);
sem_post(&msg.full);
}
}
//消费者工作
void *consum(void *p)
{
char buf[32] = {0};
while(1)
{
sem_wait(&msg.full);
strcpy(buf, msg.buf);
printf("消费了一个%s\n", buf);
int time = rand() % 100 + 1;
usleep(time*10000);
sem_post(&msg.empty);
}
}
int main()
{
srand ((unsigned int)time(NULL));
pthread_t produceID;
pthread_t consumID;
sem_init(&msg.empty, 0, 1);
sem_init(&msg.full, 0, 0);
//创建生产者与消费者进程
pthread_create(&produceID, NULL, produce, NULL);
pthread_create(&consumID, NULL, consum, NULL);
//等待线程结束
pthread_join(produceID,NULL);
pthread_join(consumID,NULL);
//销毁信号量
sem_destroy(&msg.empty);
sem_destroy(&msg.full);
return 0;
}
生产者与消费者模型
最新推荐文章于 2022-12-13 20:54:48 发布