Skip to content
Snippets Groups Projects
Commit d19e6d09 authored by kadsendino's avatar kadsendino
Browse files

Aufgabe 3

parent dd867a39
No related branches found
No related tags found
No related merge requests found
// 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;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment