线程——消费者生产者

来源:互联网 发布:巫师2优化补丁 编辑:程序博客网 时间:2024/06/01 09:09
#include <stdio.h>
#include <pthread.h>
#include <time.h>
#include <string.h>


int resources;


pthread_mutex_t mutex;


void delay()
{
unsigned int x,y;
x = rand()%10000+1;
while (x > 0)
{
y = rand()%10000+1;
while (y > 0)
{
y--;
}
x--;
}


}


void *producer(void *arg)
{
while (1)
{
pthread_mutex_lock(&mutex);

delay();
resources += 2;
printf("Produce 2 resources\n");

pthread_mutex_unlock(&mutex);
}
}


void *consumer(void *arg)
{
while (1)
{
pthread_mutex_lock(&mutex);

if (resources <= 0)
{
pthread_mutex_unlock(&mutex);
continue;
}
delay();
resources--;
printf("Consumer 1 resources, %d left\n", resources);

pthread_mutex_unlock(&mutex);
}
}


int main()
{
pthread_t p1, c1, c2, c3;
int err;


srand((unsigned int)time(NULL));


pthread_mutex_init(&mutex, NULL);


err = pthread_create(&p1, NULL, producer, NULL);
if (-1 == err)
{
printf("create p1 thread fail: %s\n", strerror(err));
return -1;
}


err = pthread_create(&c1, NULL, consumer, NULL);
if (-1 == err)
{
printf("create c1 thread fail: %s\n", strerror(err));
return -1;
}


err = pthread_create(&c2, NULL, consumer, NULL);
if (-1 == err)
{
printf("create c2 thread fail: %s\n", strerror(err));
return -1;
}


err = pthread_create(&c3, NULL, consumer, NULL);
if (-1 == err)
{
printf("create c3 thread fail: %s\n", strerror(err));
return -1;
}


err = pthread_join(p1, NULL);
if (0 != err)
{
printf("wait p1 thread fail: %s\n", strerror(err));
return -1;
}


err = pthread_join(c1, NULL);
if (0 != err)
{
printf("wait c1 thread fail: %s\n", strerror(err));
return -1;
}


err = pthread_join(c2, NULL);
if (0 != err)
{
printf("wait c2 thread fail: %s\n", strerror(err));
return -1;
}


err = pthread_join(c3, NULL);
if (0 != err)
{
printf("wait c3 thread fail: %s\n", strerror(err));
return -1;
}


pthread_mutex_destroy(&mutex);


return 0;
}
原创粉丝点击