linux多进程生产消费,linux 多线程 生产者 消费者

#include

#include

#include

#include

static const int max_capacity = 8;

static int capacity = 0;

static int n_consumed = 0;

static pthread_mutex_t lock_p;

static pthread_mutex_t lock_c;

void *produce(void *arg)

{

pthread_detach(pthread_self());

static int n_produced = 0;

for (;;) {

pthread_mutex_lock(&lock_p);

if (capacity == max_capacity) {

printf("缓冲区已满,不再生产\n");

} else {

++capacity;

printf("生产一个产品后:%d\n", capacity);

++n_produced;

if (n_produced == max_capacity) {

pthread_mutex_unlock(&lock_c);

pthread_exit(0);

}

}

pthread_mutex_unlock(&lock_c);

}

}

void *consume(void *arg)

{

pthread_detach(pthread_self());

for (;;) {

pthread_mutex_lock(&lock_c);

if (capacity == 0) {

printf("缓冲区为空,不能消费\n");

} else {

--capacity;

printf("消费一个产品后:%d\n", capacity);

++n_consumed;

if (n_consumed == max_capacity) {

pthread_mutex_unlock(&lock_p);

pthread_exit(0);

}

}

pthread_mutex_unlock(&lock_p);

}

}

int TestProducerComsumer()

{

if (capacity == 0)

pthread_mutex_lock(&lock_c);

else if (capacity == max_capacity)

pthread_mutex_lock(&lock_p);

int ret;

pthread_t producer;

ret = pthread_create(&producer, nullptr, produce, nullptr);

if (ret != 0) {

printf("pthread_create producer failed, %s\n", strerror(ret));

return -1;

}

const int n_consumers = 3;

pthread_t consumers[n_consumers];

for (int i = 0; i < n_consumers; ++i) {

ret = pthread_create(&consumers[i], nullptr, consume, nullptr);

if (ret != 0) {

printf("pthread_create consumer %d failed, %s\n", i, strerror(ret));

return -1;

}

}

sleep(5);//线程运行时调用了pthread_detach(...)函数,为了看到线程的输出

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值