线程——消费者生产者

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值