用多线程实现生产者消费者:
内容比较搞笑生动,更容易理解,有什么不懂得可以在下面留言
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
int count = 1;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void * p_cre1(void * arg)
{
printf ("大家好,我是小明,我相信工作的人最美丽 \n不多说了,我要开始搬砖了\n");
pthread_mutex_lock(&mutex);
printf ("今天我一定要搬够一百块砖!\n");
printf ("努力工作中");
for (count = 1;count < 100 ; ++count)
{
printf (".");
if (count == 99)
printf ("\n好了,我搬够一百块金砖了 \n");
}
printf ("累死我了,让我休息会 \n");
if(count >= 100)
{
pthread_cond_signal(&cond);
}
pthread_mutex_unlock(&mutex);
return NULL;
}
void * p_cre2(void * arg)
{
printf ("\n\n\n大家好,我是小刚,我相信努力就会有收获 \n我要努力搬砖了,不能被小明比下去\n");
printf ("哇,小明都搬了%d块砖了啊,我也要努力了 \n",count);
pthread_mutex_lock(&mutex);
printf ("今天我也一定要搬够一百块砖!\n");
printf ("努力工作中");
for (count ;count <= 200 ; count ++)
{
printf (".");
if (count == 200)
printf ("\n好了,我也搬够一百块金砖了 \n");
}
printf ("我也休息会吧 \n");
if(count >= 200)
{
pthread_cond_signal(&cond);
}
pthread_mutex_unlock(&mutex);
return NULL;
}
void * p_con1(void * arg)
{
printf ("\n\n\n嘿嘿嘿,听说小明小刚今天搬了不少砖,我乘他们休息,去 “借 ”几块\n");
pthread_mutex_lock(&mutex);
if(count <= 0)
{
printf("不对啊,怎么都没有了,真是奇怪啊\n\n\n");
printf("唉,先走吧,一会再来看看\n");
pthread_cond_wait(&cond,&mutex);
printf("\n嘿嘿嘿,这次有了\n");
}
if(count = 200)
{
printf("我就先借一半吧\n");
for (count;count > 100;--count)
{
if (count = 100)
printf ("恩恩,100块砖也暂时够我用了 \n");
}
}
pthread_mutex_unlock(&mutex);
return NULL;
}
void * p_con2(void * arg)
{
printf ("\n\n\n嘿嘿嘿,刚听老王说小明小刚今天搬了不少砖,我也乘他们休息,去 “借 ”几块\n");
pthread_mutex_lock(&mutex);
if(count <= 0)
{
printf("不对啊,怎么都没有了,真是奇怪啊\n");
printf("唉,先走吧,一会再来看看\n");
pthread_cond_wait(&cond,&mutex);
printf("嘿嘿嘿,这次有了\n");
}
if(count = 100)
{
printf("老王借了一半那我也就先借一半吧\n");
for (count;count > 50;--count)
{
if (count = 50)
printf ("恩恩,50块砖也暂时够我用了 \n");
}
}
pthread_mutex_unlock(&mutex);
return NULL;
}
int main()
{
pthread_t cre1,cre2,con1,con2;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setschedpolicy(&attr,SCHED_FIFO);
pthread_create(&con1, NULL, p_con1, NULL);//第一个消费者
sleep (1);
pthread_create(&cre1, NULL, p_cre1, NULL); //第一个生产者
sleep (1);
pthread_create(&cre2, NULL, p_cre2, NULL);//第二个生产者
sleep (1);
pthread_create(&con2, NULL, p_con2, NULL);//第二个消费者
pthread_join(cre1, NULL);
pthread_join(cre2, NULL);
pthread_join(con1, NULL);
pthread_join(con2, NULL);
return 0;
}