#include<myhead.h>
pthread_mutex_t fastmutex;//定义互斥锁
pthread_cond_t cond;//定义条件变量
#define MAX 5
void *product_fun(void *arg)
{
while(1)
{
sleep(1);
printf("生产一个苹果\n");
pthread_cond_signal(&cond);//唤醒一个线程
}
pthread_exit(NULL);
}
void *customer_fun(void *arg)
{
int i = 0;
while(i<MAX){
pthread_mutex_lock(&fastmutex);//上互斥锁
pthread_cond_wait(&cond,&fastmutex);//等待线程被唤醒:
printf("我买一个苹果\n");
pthread_mutex_unlock(&fastmutex);
i++;
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
pthread_mutex_init(&fastmutex,NULL);//初始化锁
pthread_cond_init(&cond,NULL);//初始化条件变量
pthread_t product,customer[MAX];
if(pthread_create(&product,NULL,product_fun,NULL)!=0)
{
perror("create");
return -1;
}
int i = 0;
while(i<MAX){
if(pthread_create(&customer[i],NULL,customer_fun,NULL)!=0)
{
perror("create");
return -1;
}
i++;
}
i =0;
while(i<MAX)
{
pthread_join(customer[i],NULL);
}
pthread_join(product,NULL);
pthread_mutex_destroy(&fastmutex);
pthread_cond_destroy(&cond);
return 0;
}