myFirstRep/race.c

39 lines
1.4 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// Created by mrnek on 25.05.2023.
//
#include "race.h"
void * participant(void *arg) { // Функция для участника гонки
info->participants_in_tunnel = 0;
info->participants_finished = 0;
int participant_id = *(int *)arg;
// Подготовка участника
printf("Участник %d готовится к гонке\n", participant_id);
// Ожидание начала гонки
pthread_mutex_lock(info->tunnel_mutex);
while (info->participants_in_tunnel >= TUNNEL_CAPACITY) {
// Ждем, пока не освободится место в тоннеле
pthread_cond_wait(info->start_cond, info->tunnel_mutex);
}
info->participants_in_tunnel++;
pthread_mutex_unlock(info->tunnel_mutex);
printf("Участник %d начинает гонку\n", participant_id);
// Гонка
// Завершение гонки
pthread_mutex_lock(info->tunnel_mutex);
info->participants_finished++;
if (info->participants_finished == NUM_PARTICIPANTS) {
// Если все участники закончили гонку, уведомляем о завершении
pthread_cond_broadcast(info->finish_cond);
}
pthread_mutex_unlock(info->tunnel_mutex);
printf("Участник %d закончил гонку\n", participant_id);
pthread_exit(NULL);
}