Untitled
unknown
plain_text
2 years ago
1.5 kB
6
Indexable
#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;
}
void scanFunction() {
int trainNumber;
printf("Enter the train number (1 to %d): ", NUM_TRAINS);
scanf("%d", &trainNumber);
// Check if the entered train number is valid
if (trainNumber >= 1 && trainNumber <= NUM_TRAINS) {
// Create a thread for the scanned train
pthread_t scanThread;
pthread_create(&scanThread, NULL, train, (void*)&trainNumber);
// Wait for the scan thread to finish
pthread_join(scanThread, NULL);
} else {
printf("Invalid train number. Please enter a number between 1 and %d.\n", NUM_TRAINS);
}
}
int main() {
srand(time(NULL));
// Initialize semaphore with initial value 1
sem_init(&trackSemaphore, 0, 1);
// Ask the user to scan a train
scanFunction();
// Destroy semaphore
sem_destroy(&trackSemaphore);
return 0;
}
Editor is loading...
Leave a Comment