qfedu-linux-advanced-level/day7/condition.c

84 lines
1.9 KiB
C

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
// 条件变量实例
// 互斥锁和条件变量的初始化
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void *producer_task(void *data)
{
int *n = (int *)data;
while (1)
{
pthread_mutex_lock(&mutex);
while (*n == 10) // 只要资源为 10 ,就等待
{
// 条件变量等待后,会自动释放 mutex 锁
pthread_cond_wait(&cond, &mutex);
}
(*n)++;
printf("生产线程(%ld)生产了 %d 个产品\n", pthread_self(), *n);
// 发出通知,让等待消费的线程恢复(条件满足)
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
// usleep(200 * 1000);
sleep(1);
}
pthread_exit(NULL);
}
void *consumer_task(void *data)
{
int *n = (int *)data;
while (1)
{
pthread_mutex_lock(&mutex);
while (*n == 0) // 只要资源为 0 ,就等待
{
// 条件变量等待后,会自动释放 mutex 锁
pthread_cond_wait(&cond, &mutex);
}
printf("消费者(%ld) 消费了 %d 产品\n", pthread_self(), *n);
(*n)--;
pthread_mutex_unlock(&mutex);
// usleep(200 * 1000);
sleep(1);
}
pthread_exit(NULL);
}
int main(int argc, char const *argv[])
{
int num = 3; // 3 个产品
pthread_t threads[10];
// 创建 2 个生产线程
for (int i = 0; i < 8; i++)
{
pthread_create(&threads[i], NULL, producer_task, &num);
}
// 创建 3 个消费者线程
for (int i = 8; i < 10; i++)
{
pthread_create(&threads[i], NULL, consumer_task, &num);
}
for (int i = 0; i < 10; i++)
{
pthread_join(threads[i], NULL);
}
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}