diff --git a/aufgabe04/aufgabe3.c b/aufgabe04/aufgabe3.c new file mode 100644 index 0000000000000000000000000000000000000000..5bf076979ba8f1edf4eef4d88f30bf658afe853f --- /dev/null +++ b/aufgabe04/aufgabe3.c @@ -0,0 +1,64 @@ +// dining philosophers with unshared chopsticks +#include <stdio.h> +#include <stdlib.h> +#include <pthread.h> +#include <semaphore.h> +#include <unistd.h> + +#define NUM_THREADS 5 +sem_t chopsticks[NUM_THREADS]; + +void* Philosopher (void *threadid) +{ + long tid; + tid = (long)threadid; + + for (int i= 0; i < 10; i++) { + // thinking + sleep (0.5); + + //wait + + sem_wait(&chopsticks[tid]); + sem_wait(&chopsticks[(tid+1) % NUM_THREADS]); + + printf("%ld Dining..\n", tid); + sleep(0.5); + printf("%ld Finished..\n", tid); + + sem_post(&chopsticks[tid]); + sem_post(&chopsticks[(tid+1) % NUM_THREADS]); + } +} + + +int main (void) +{ + pthread_t threads[NUM_THREADS]; + int rc; + long t; + + for(int i=0;i<NUM_THREADS;i++){ + sem_init(&chopsticks[i],0,1); + } + + for(t=0; t < NUM_THREADS; t++) { + printf ("In main: creating thread %ld\n", t); + rc = pthread_create (&threads[t], NULL, Philosopher, (void *)t); + if (rc) { + printf ("ERROR; return code from pthread_create () is %d\n", rc); + exit (-1); + } + } + + for(t=0; t < NUM_THREADS; t++) { + pthread_join (threads[t], NULL); + } + + for(int i=0;i<NUM_THREADS;i++){ + sem_destroy(&chopsticks[i]); + } + + return 0; +} +