#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
/* TO DO:借助条件变量模拟生产者-消费者问题 */
// 链表作为公共数据,被互斥量保护
struct msg{
struct mst *next;
int num;
};
struct msg* head;
// 静态初始化互斥锁和条件变量
pthread_cond_t has_product = PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
// 模拟消费者
void *consumer(void *p)
{
struct msg *mp;
for (;;) {
pthread_mutex_lock(&lock); // 加锁
while (head == NULL)
pthread_cond_wait(&has_product, &lock); // 等待信号
mp = head; // 模拟消费
head = mp->next;
pthread_mutex_unlock(&lock); // 解锁
printf("Consume -------- %d\n", mp->num);
free(mp); // 释放指针
sleep(rand()%5);
}
return NULL;
}
// 模拟生产者
void *producter(void *p)
{
struct msg *pro;
for (;;){
pro = malloc(sizeof(struct msg)); // 分配内存
pro->num = rand()%1000+1;
printf("Produce -------- %d\n", pro->num);
pthread_mutex_lock(&lock); // 加锁
pro->next = head; // 模拟生产
head = pro;
pthread_mutex_unlock(&lock); // 解锁
pthread_cond_signal(&has_product); // 给条件变量发送信号
sleep(rand()%5);
}
return NULL;
}
int main(int argc, char* argv[])
{
pthread_t pid, cid;
srand(time(NULL));
// 创建生产者消费者线程
pthread_create(&pid, NULL, producter, NULL);
pthread_create(&cid, NULL, consumer, NULL);
// 回收线程
pthread_join(pid, NULL);
pthread_join(cid, NULL);
return 0;
}