Skip to content
Snippets Groups Projects

Übung2

Open omah03 requested to merge omah03/alp4-repo-template:Übung2 into main
1 file
+ 71
0
Compare changes
  • Side-by-side
  • Inline
cars.c 0 → 100644
+ 71
0
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#define NUM_CARS 2
#define NUM_CROSSES 100000
pthread_mutex_t bridge_mutex = PTHREAD_MUTEX_INITIALIZER;
int bridge_count = 0;
int cross_count = 0;
void *cross_bridge(void *arg) {
int id = *(int *) arg;
int i;
for (i = 0; i < NUM_CROSSES; i++) {
// Wait before crossing the bridge
usleep(rand() % 10000);
// Try to acquire the bridge mutex
pthread_mutex_lock(&bridge_mutex);
// Check if the bridge is already occupied
if (bridge_count > 0) {
printf("Car %d waiting at bridge (cross %d)\n", id, cross_count);
}
// Increment the bridge count
bridge_count++;
// Release the bridge mutex
pthread_mutex_unlock(&bridge_mutex);
// Cross the bridge
printf("Car %d crossing bridge (cross %d)\n", id, cross_count);
cross_count++;
usleep(rand() % 10000);
// Try to acquire the bridge mutex again
pthread_mutex_lock(&bridge_mutex);
// Decrement the bridge count
bridge_count--;
// Release the bridge mutex
pthread_mutex_unlock(&bridge_mutex);
}
pthread_exit(NULL);
}
int main() {
int i;
pthread_t cars[NUM_CARS];
int ids[NUM_CARS];
// Initialize the random number generator
srand(time(NULL));
// Create the cars
for (i = 0; i < NUM_CARS; i++) {
ids[i] = i + 1;
pthread_create(&cars[i], NULL, cross_bridge, &ids[i]);
}
// Wait for the cars to finish
for (i = 0; i < NUM_CARS; i++) {
pthread_join(cars[i], NULL);
}
return 0;
}
Loading