C-Code für das Problem der speisenden Philosophen

Informatik3,96 KB

Implementierung des Problems der speisenden Philosophen in C

num_filosofos int = 0; int seed = 0; int i, res;

Globale Variablen und Hilfsfunktionen

// Stellgrößen
pthread_mutex_t *Inhaber; // Array von Mutex
// struct timeval time;, für die Funktion gettimeofday
timeIni long;, zeigt die erste Zeit

lange dameTiempo () // gibt Zeit in einer bestimmten Zeit in Millisekunden zurück
(
struct timeval zeit;
gettimeofday (&zeit, NULL);
return (long) (tiempo.tv_sec * 1000 + tiempo.tv_usec/1000);
)

Funktion: Essen

int essen (int n)
(
TimeWait lang;
TimeWait = rand () % 501; // Zufallszahl zwischen 0 und 500 Millisekunden
printf ("%lu:%d Philosoph ißt \n", (dameTiempo () - timeIni), n);
usleep (TimeWait * 1000); // Umrechnung in Sekunden
pthread_mutex_unlock (&(Gabel)[n]);
pthread_mutex_unlock (&(Gabeln)[(n + 1) % num_filosofos]);
return 0;
)

Funktion: Schlafen

int sleep (int n)
(
TimeWait lang;
TimeWait = rand () % 501; // Zufallszahl zwischen 0 und 500 ms
printf ("%lu:%d Tutor schlafen \n", (dameTiempo () - timeIni), n);
usleep (TimeWait * 1000);
return 0;
)

Philosophen-Thread

void *Philosoph (void *arg)
(
long n = (long) arg;
while (1)
(
if (pthread_mutex_trylock (&(Gabel)[n]) == 0) // Versuche, die Gabel auf der einen Seite zu nehmen, und wenn diese...
(
if ((pthread_mutex_trylock (&(Gabeln)[(n + 1) % num_filosofos]) == 0)) // ...versuche, die andere Gabel zu nehmen, und wenn das klappt, essen und schlafen
(
essen(n), Schlafstörungen(n);
)
else // wenn nur eine verfügbar ist, schlafen
(
pthread_mutex_unlock (&(Gabel)[n]);
Schlafstörungen(n);
)
)
// Wenn die erste nicht verfügbar ist, schlafen...
else
sleep (n);
)
)

Hauptfunktion (Main)

int main (int argc, char *argv[])
(
int result = handle_options (argc, argv);
long i;
if (result != 0)
exit (result);
printf ("Number of Philosophen %d, Saatgut %d \n", num_filosofos, Saatgut);
// TOP Samen in die Kontrolle der Dienstleistungs-KONTROLLE DER PASSAGE DER PARAMETER
// Wir setzen die erste Zeit in Millisekunden.
timeIni = dameTiempo ();
// Create the mutex nach initializmos Inhaber und die Zahl der Philosophen
Gabeln = malloc (num_filosofos * sizeof (pthread_mutex_t)); // Reserve Speicherplatz für die Inhaber
if (Gabeln == NULL)
(
perror ("Not enough memory");
exit (0);
)
for (i = 0; i < num_filosofos; i++)
(
res = pthread_mutex_init (&(Gabel)[i], NULL);
if (res != 0)
(
perror ("Fehler bei der Initialisierung Mutex");
exit (0);
)
)
// Create a thread (nach der Zahl der Philosophen) und initialisiert
for (i = 1; i <= num_filosofos; i++)
(
pthread_t tid; // zur Ermittlung der Fäden
res = pthread_create (&tid, NULL, Philosoph, (void *) i);
if (res < 0)
perror ("creating thread");
)
Schlaf(60);
exit (0);
)

Herunterladen

PDF Word HTML