多任务互斥与同步(互斥锁, 读写锁, 条件变量, 信号量, 命名信号量): 作业1,2,3,4,5

This commit is contained in:
flykhan 2023-08-23 00:24:34 +08:00
parent 721846a61d
commit ffc2656985
1 changed files with 87 additions and 0 deletions

87
day7/homework/h5.c Normal file
View File

@ -0,0 +1,87 @@
/*
, 线, 线, 线线, ,
*/
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
// 互斥锁和条件变量初始化
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_p = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond_c = PTHREAD_COND_INITIALIZER;
int current = 0;
int max = 100;
int min = 0;
void *producer(void *data)
{
while (1)
{
pthread_mutex_lock(&mutex); // 生产者加锁
while (current == max)
{
pthread_cond_wait(&cond_p, &mutex);
}
current++;
printf("+++++++++++++++++++++生成者 %ld 完成生产, 仓库剩余 %d 个商品\n", pthread_self(), current);
pthread_cond_broadcast(&cond_c); // 发出通知,让等待消费的线程恢复(条件满足)
pthread_mutex_unlock(&mutex); // 生产者解锁
usleep(100 * 1000);
}
pthread_exit(NULL);
}
void *consumer(void *data)
{
while (1)
{
pthread_mutex_lock(&mutex); // 消费者加锁
while (current == min)
{
pthread_cond_wait(&cond_c, &mutex);
}
current--;
printf("----------------------消费者 %ld 完成消费, 仓库剩余 %d 个商品\n", pthread_self(), current);
pthread_cond_broadcast(&cond_p);
pthread_mutex_unlock(&mutex);
usleep(150 * 1000);
}
pthread_exit(NULL);
}
int main(int argc, char const *argv[])
{
// 生产者线程
const int num_producer = 10; // 生产者数量
pthread_t t_producer[num_producer];
for (int i = 0; i < num_producer; i++)
{
pthread_create(&t_producer[i], NULL, producer, NULL);
}
// 消费者线程
const int num_consumer = 10; // 消费者数量
pthread_t t_consumer[num_consumer];
for (int i = 0; i < num_consumer; i++)
{
pthread_create(&t_consumer[i], NULL, consumer, NULL);
}
// join
for (int i = 0; i < num_producer; i++)
{
pthread_join(t_producer[i], NULL);
}
for (int i = 0; i < num_consumer; i++)
{
pthread_join(t_consumer[i], NULL);
}
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond_c);
pthread_cond_destroy(&cond_p);
return 0;
}