Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
2.2 kB
1
Indexable
Never
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>

#define NUM_RUNWAYS 3
#define NUM_AIRPLANES 5

sem_t runways[NUM_RUNWAYS];
pthread_mutex_t log_mutex = PTHREAD_MUTEX_INITIALIZER;

void log_message(const char *message) {
    pthread_mutex_lock(&log_mutex);
    printf("%s\n", message);
    pthread_mutex_unlock(&log_mutex);
}

void *airplane_thread(void *arg) {
    int airplane_id = *(int *)arg;
    srand((unsigned int)time(NULL) + airplane_id);

    // Simulate random decision to land or take off
    int decision = rand() % 2; // 0 for landing, 1 for taking off

    if (decision == 0) {
        log_message("Airplane %d is requesting permission to land.");
    } else {
        log_message("Airplane %d is requesting permission to take off.");
    }

    for (int i = 0; i < NUM_RUNWAYS; ++i) {
        if (sem_trywait(&runways[i]) == 0) {
            if (decision == 0) {
                log_message("Airplane %d has landed on Runway %d.", airplane_id, i);
                sleep(2); // Simulating the landing process
                log_message("Airplane %d has taken off from Runway %d.", airplane_id, i);
            } else {
                log_message("Airplane %d has taken off from Runway %d.", airplane_id, i);
            }
            
            sem_post(&runways[i]); // Release the runway after landing/taking off
            break;
        }
    }

    pthread_exit(NULL);
}

int main() {
    pthread_t airplanes[NUM_AIRPLANES];
    int airplane_ids[NUM_AIRPLANES];

    // Initialize semaphores
    for (int i = 0; i < NUM_RUNWAYS; ++i) {
        sem_init(&runways[i], 0, 1); // Initial value of 1 (available)
    }

    // Create airplane threads
    for (int i = 0; i < NUM_AIRPLANES; ++i) {
        airplane_ids[i] = i + 1;
        pthread_create(&airplanes[i], NULL, airplane_thread, &airplane_ids[i]);
    }

    // Join threads
    for (int i = 0; i < NUM_AIRPLANES; ++i) {
        pthread_join(airplanes[i], NULL);
    }

    // Destroy semaphores
    for (int i = 0; i < NUM_RUNWAYS; ++i) {
        sem_destroy(&runways[i]);
    }

    return 0;
}
Leave a Comment