Untitled

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



sem_t runways[10];
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 < 10; ++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): ", 10);
    scanf("%d", &num_runways);

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

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

    if (num_airplanes <= 0 || num_airplanes > 100) {
        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;
}
Leave a Comment