条件变量实现如下:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
//节点结构体
struct msg
{
int num; //数据区
struct msg *next; //链表区
};
struct msg *head = NULL;//头指针
//struct msg *mp = NULL; //节点指针
//利用宏定义的方式初始化全局的互斥锁和条件变量
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t has_product = PTHREAD_COND_INITIALIZER;
void *producter(void *arg)
{
struct msg *mp;
while (1)
{
mp = malloc(sizeof(struct msg));
mp->num = rand() % 400 + 1;
printf("---producted---%d\n", mp->num);
pthread_mutex_lock(&mutex);//访问共享区域必须加锁
mp->next = head;
head = mp;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&has_product);//通知消费者来消费
sleep(rand() % 3);
}
return NULL;
}
void *consumer(void *arg)
{
struct msg *mp;
while (1)
{
pthread_mutex_lock