首先是用信号量实现的
#include <stdio.h>
#include <pthread.h>
#include <time.h>
#include <string.h>
#include <semaphore.h>
//信号量和缓冲区
struct data
{
sem_t producer; //用来控制生产者,只有缓冲区为空,生产者才可以生产消息
sem_t customer; //用来控制消费者,只有缓冲区有数据,才可以消费
char buf[32]; //缓冲区
};
struct data model;
void* producer_do(void *a)
{
char *buf[] = {"香蕉","菠萝","橙子","西瓜","苹果","黄瓜","橘子"};
while(1)
{
int time = rand() % 100 + 1;
usleep(time* 10000);
sem_wait(&model.producer); // p
strcpy(model.buf,buf[rand()%7]);
printf("生产的一个水果:%s\n",model.buf);
sem_post(&model.customer); // v
}
}
void* customer_do(void *a)
{
while(1)
{
int time = rand() % 100 + 1;
usleep(time* 10000);
sem_wait(&model.customer); // p
printf("吃了一个水果:%s\n",model.buf);
sem_post(&model.producer); // v
}
}
int main()
{
srand((unsigned int)time(NULL));
//信号量初始化
sem_init(&model.producer,0,1);
sem_init(&model.customer,0,0);
pthread_t producer_id;
pthread_t customer_id;
//生产者线程
pthread_create(&producer_id,NULL,producer_do,NULL);
//消费者线程
pthread_create(&customer_id,NULL,customer_do,NULL);
//等待线程
pthread_join(producer_id,NULL);
pthread_join(customer_id,NULL);
//销毁信号量
sem_destroy(&model.producer);
sem_destroy(&model.customer);
return 0;
}
然后再加上互斥锁的
#include <stdio.h>
#include <pthread.h>
#include <time.h>
//#include <string.h>
#include <semaphore.h>
#include "SqQuenue.h"
//声明信号量
struct data
{
sem_t producer;
sem_t customer;
QUEUE q;
};
//互斥锁
pthread_mutex_t mutex;
//创建信号量
struct data model;
//创建计数
Queue_data num = 0;
//生产者线程
void* producer_do(void *a)
{
while(1)
{
int time = rand() % 100 + 1;
usleep(time* 10000);
sem_wait(&model.producer); // p
pthread_mutex_lock(&mutex); //开锁
num++;
PushQueue(&(model.q),num);
printf("生产了一个编号为%d的水果\n",num);
pthread_mutex_unlock(&mutex); //解锁
sem_post(&model.customer); // v
}
}
//消费者线程
void* customer_do(void *a)
{
while(1)
{
int time = rand() % 100 + 1;
usleep(time* 10000);
sem_wait(&model.customer); // p
pthread_mutex_lock(&mutex); //开锁
Queue_data x;
PopQueue(&(model.q),&x);
printf("消费了一个编号为%d的水果\n",x);
pthread_mutex_unlock(&mutex); //解锁
sem_post(&model.producer); // v
}
}
int main()
{
srand((unsigned int)time(NULL));
//信号量初始化
sem_init(&model.producer,0,10);
sem_init(&model.customer,0,0);
//初始化互斥锁
pthread_mutex_init(&mutex, NULL);
//初始化队列
Initqueue(&(model.q));
pthread_t producer_id;
pthread_t customer_id;
//生产者线程
pthread_create(&producer_id,NULL,producer_do,NULL);
//消费者线程
pthread_create(&customer_id,NULL,customer_do,NULL);
//等待线程
pthread_join(producer_id,NULL);
pthread_join(customer_id,NULL);
//销毁信号量
sem_destroy(&model.producer);
sem_destroy(&model.customer);
//销毁互斥锁
pthread_mutex_destroy(&mutex);
return 0;
}