#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;
}