1 |
|
|
2 |
|
#include <stdlib.h> |
3 |
|
#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 ) { |
16 |
|
|
17 |
|
int i; |
18 |
|
|
19 |
|
/* Datenstruktur "erzeugen" */ |
20 |
|
*sec = malloc(sizeof(struct _crit_sec)); |
21 |
|
|
22 |
|
/* Datenstruktur mit "0" initialisieren */ |
23 |
|
for (i = 0; i < MAX_THREADS; i++) { |
24 |
|
(*sec)->choosing[i] = 0; |
25 |
|
(*sec)->number[i] = 0; |
26 |
|
} |
27 |
|
|
28 |
|
} |
29 |
|
|
30 |
|
void My_DeleteCriticalSection( MY_LPCRITICAL_SECTION sec ) { |
31 |
|
|
32 |
|
/* Datenstruktur freigeben */ |
33 |
|
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 |
|
} |