| 2 |
#include <stdlib.h> |
#include <stdlib.h> |
| 3 |
#include "bakery.h" |
#include "bakery.h" |
| 4 |
|
|
| 5 |
|
int maxValueInList(int list[], int list_length) { |
| 6 |
|
int i; |
| 7 |
|
int max_value = 0; |
| 8 |
|
for (i = 0; i < list_length; i++) { |
| 9 |
|
if (list[i] > max_value) |
| 10 |
|
max_value = list[i]; |
| 11 |
|
} |
| 12 |
|
return max_value; |
| 13 |
|
} |
| 14 |
|
|
| 15 |
void My_InitializeCriticalSection( MY_LPCRITICAL_SECTION * sec ) { |
void My_InitializeCriticalSection( MY_LPCRITICAL_SECTION * sec ) { |
| 16 |
|
|
| 17 |
int i; |
int i; |
| 33 |
free(sec); |
free(sec); |
| 34 |
|
|
| 35 |
} |
} |
| 36 |
|
|
| 37 |
|
void My_EnterCriticalSection( int ThId, MY_LPCRITICAL_SECTION sec ) { |
| 38 |
|
|
| 39 |
|
int j; |
| 40 |
|
|
| 41 |
|
/* Beginn der Ticket-ID Berechnung */ |
| 42 |
|
sec->choosing[ThId] = 1; |
| 43 |
|
|
| 44 |
|
/* Neue Ticket-ID berechnen */ |
| 45 |
|
sec->number[ThId] = maxValueInList(sec->number, MAX_THREADS) + 1; |
| 46 |
|
|
| 47 |
|
/* Ende der Ticket-ID Berechnung */ |
| 48 |
|
sec->choosing[ThId] = 0; |
| 49 |
|
|
| 50 |
|
/* Alle Threads durchlaufen */ |
| 51 |
|
for (j = 0; j < MAX_THREADS; j++) { |
| 52 |
|
|
| 53 |
|
/* warten, falls ein anderer Thread momentan eine Ticket-ID berechnet (busy wait) */ |
| 54 |
|
while (sec->choosing[j] == 1); |
| 55 |
|
|
| 56 |
|
while ( (sec->number[j] != 0) && |
| 57 |
|
( |
| 58 |
|
(sec->number[j] < sec->number[ThId]) || |
| 59 |
|
((sec->number[j] == sec->number[ThId]) && j < ThId) |
| 60 |
|
) |
| 61 |
|
); |
| 62 |
|
|
| 63 |
|
} |
| 64 |
|
|
| 65 |
|
} |
| 66 |
|
|
| 67 |
|
void My_LeaveCriticalSection( int ThId, MY_LPCRITICAL_SECTION sec ) { |
| 68 |
|
sec->number[ThId] = 0; |
| 69 |
|
} |