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

Aufgabe04-1

parent 83435db3
Branches master
No related tags found
No related merge requests found
File mode changed from 100644 to 100755
aufgabe1.o: aufgabe1.c
File deleted
File deleted
# This makefile compiles all C files in the same directory and produces a single
# executable named solution
CC = gcc
CFLAGS = -std=c11 -Wall -Wextra -pedantic -O2 -g -pthread # this uses the C11 standard, if you want to use a different standard, change it to -std=c[NUMBER]
CPPFLAGS = -MMD
LD_FLAGS = -lm
BIN_NAME = solution
SRC_FILES = $(wildcard *.c)
OBJ_FILES = $(SRC_FILES:.c=.o)
DEP_FILES = $(wildcard *.d)
run: $(BIN_NAME)
./$(BIN_NAME)
include $(DEP_FILES)
$(BIN_NAME): $(OBJ_FILES)
$(CC) $(CPPFLAGS) $(LD_FLAGS) $(OBJ_FILES) -o $@
%.o: %.c
$(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $@
clean:
@rm -v *.o *.d
@rm -v ./$(BIN_NAME)
.PHONY: run clean
// dining philosophers with unshared chopsticks
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#define NUM_THREADS 5
pthread_mutex_t lock;
int chopsticks[NUM_THREADS];
void* Philosopher (void *threadid)
{
long tid;
tid = (long)threadid;
int _error = 0;
for (int i= 0; i < 10; i++) {
// thinking
sleep (0.5);
//wait
//Beginn kritischer Abschnitt
_error = pthread_mutex_lock(&lock);
//Warten darauf, dass chopstick frei werden
while (chopsticks[tid] + chopsticks[(tid + 1) % NUM_THREADS] < 2);
chopsticks[tid] = 0;
chopsticks[(tid + 1) % NUM_THREADS] = 0;
_error = pthread_mutex_unlock(&lock);
//Ende kritischer Abschnitt
printf("\n %ld Dining..\n", tid);
sleep(0.5);
printf("\n %ld Finished..\n", tid);
//Beginn kritischer Abschnitt
_error = pthread_mutex_lock(&lock);
chopsticks[tid] = 1;
chopsticks[(tid + 1) % NUM_THREADS] = 1;
_error = pthread_mutex_unlock(&lock);
//Ende kritischer Abschnitt
}
}
int main (void)
{
pthread_t threads[NUM_THREADS];
int rc;
long t;
for(int i=0;i<NUM_THREADS;i++){
chopsticks[i]=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);
}
return 0;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment