Untitled

 avatar
unknown
plain_text
a year ago
2.8 kB
3
Indexable
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>

#define MAX_RUNWAYS 10
#define MAX_AIRPLANES 100

sem_t runways[MAX_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 < MAX_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() {
    int num_runways, num_airplanes;

    printf("Enter the number of runways (max %d): ", MAX_RUNWAYS);
    scanf("%d", &num_runways);

    if (num_runways <= 0 || num_runways > MAX_RUNWAYS) {
        printf("Invalid number of runways. Exiting.\n");
        return 1;
    }

    printf("Enter the number of airplanes (max %d): ", MAX_AIRPLANES);
    scanf("%d", &num_airplanes);

    if (num_airplanes <= 0 || num_airplanes > MAX_AIRPLANES) {
        printf("Invalid number of airplanes. Exiting.\n");
        return 1;
    }

    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;
}
Editor is loading...
Leave a Comment