Untitled

 avatar
unknown
plain_text
2 years ago
2.5 kB
5
Indexable
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>

sem_t track_semaphore;
pthread_mutex_t log_lock;
int train_count = 0;
int completed_trains = 0;
int total_trains;
int track_capacity;

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

void train_movement(int train_id, const char* action) {
    char message[50];
    sprintf(message, "Train %d %s the track", train_id, action);
    log_message(message);
}

void* simulate_train(void* arg) {
    int train_id = *((int*)arg);
    free(arg);

    while (1) {
        // Train arriving at the track
        train_movement(train_id, "arrived at");

        // Attempt to acquire the track semaphore
        sem_wait(&track_semaphore);
        train_movement(train_id, "entered");

        // Simulate the train passing through the track
        sleep((unsigned int)(rand() % 3 + 1));

        // Train leaving the track
        train_movement(train_id, "left");
        sem_post(&track_semaphore);

        // Random wait before the next arrival
        sleep((unsigned int)(rand() % 4 + 2));

        // Increment completed train count and check for termination
        pthread_mutex_lock(&log_lock);
        completed_trains++;
        pthread_mutex_unlock(&log_lock);

        if (completed_trains == total_trains) {
            // Terminate the program after all trains have completed
            exit(0);
        }
    }

    return NULL;
}

int main() {
    // Get the track capacity from user input
    printf("Enter the track capacity: ");
    scanf("%d", &track_capacity);

    // Get the number of trains from user input
    printf("Enter the number of trains: ");
    scanf("%d", &total_trains);

    // Initialize semaphores and mutex
    sem_init(&track_semaphore, 0, track_capacity);
    pthread_mutex_init(&log_lock, NULL);

    // Create train threads
    pthread_t train_threads[total_trains];

    for (int i = 0; i < total_trains; ++i) {
        int* train_id = (int*)malloc(sizeof(int));
        *train_id = i;
        pthread_create(&train_threads[i], NULL, simulate_train, train_id);
    }

    // Wait for train threads to finish (this will not be reached)
    for (int i = 0; i < total_trains; ++i) {
        pthread_join(train_threads[i], NULL);
    }

    // Destroy semaphores and mutex (this will not be reached)
    sem_destroy(&track_semaphore);
    pthread_mutex_destroy(&log_lock);

    return 0;
}
Editor is loading...
Leave a Comment