Untitled

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

#define NUM_TRAINS 5

sem_t trackSemaphore;

void* train(void* trainID) {
    int id = *((int*)trainID);

    // Simulate arriving at the track
    sleep(rand() % 3);

    printf("Train %d is waiting to enter the track\n", id);

    // Request access to the shared track
    sem_wait(&trackSemaphore);

    printf("Train %d enters the track\n", id);

    // Simulate passing through the track
    sleep(rand() % 3);

    printf("Train %d exits the track\n", id);

    // Release the track for the next train
    sem_post(&trackSemaphore);

    return NULL;
}

int main() {
    srand(time(NULL));

    // Initialize semaphore with initial value 1
    sem_init(&trackSemaphore, 0, 1);

    pthread_t trains[NUM_TRAINS];
    int trainIDs[NUM_TRAINS];

    // Create and start train threads
    for (int i = 0; i < NUM_TRAINS; ++i) {
        trainIDs[i] = i + 1;
        pthread_create(&trains[i], NULL, train, (void*)&trainIDs[i]);
    }

    // Wait for all train threads to finish
    for (int i = 0; i < NUM_TRAINS; ++i) {
        pthread_join(trains[i], NULL);
    }

    // Destroy semaphore
    sem_destroy(&trackSemaphore);

    return 0;
}
Leave a Comment