#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <sys/time.h>
#include <sys/types.h>
int num_philosophers;
pthread_mutex_t stdout_mutex;
pthread_mutex_t random_mutex;
pthread_mutex_t *fork_mutex;
pthread_t *philosophers;
void *
xmalloc (size_t n)
{
void *p = malloc (n);
if (! p)
{
fprintf (stderr, "out of memory\n");
exit (2);
}
return p;
}
void
shared_printf (char *format, ...)
{
va_list ap;
va_start (ap, format);
pthread_mutex_lock (&stdout_mutex);
vprintf (format, ap);
pthread_mutex_unlock (&stdout_mutex);
va_end (ap);
}
int
shared_random ()
{
static unsigned int seed;
int result;
pthread_mutex_lock (&random_mutex);
result = rand_r (&seed);
pthread_mutex_unlock (&random_mutex);
return result;
}
void
my_usleep (long usecs)
{
struct timeval timeout;
timeout.tv_sec = usecs / 1000000;
timeout.tv_usec = usecs % 1000000;
select (0, 0, 0, 0, &timeout);
}
void
random_delay ()
{
my_usleep ((shared_random () % 2000) * 100);
}
void
print_philosopher (int n, char left, char right)
{
int i;
shared_printf ("%*s%c %d %c\n", (n * 4) + 2, "", left, n, right);
}
void *
philosopher (void *data)
{
int n = * (int *) data;
print_philosopher (n, '_', '_');
#if 1
if (n == num_philosophers - 1)
for (;;)
{
pthread_mutex_lock (&fork_mutex[(n + 1) % num_philosophers]);
print_philosopher (n, '_', '!');
random_delay ();
pthread_mutex_lock (&fork_mutex[n]);
print_philosopher (n, '!', '!');
random_delay ();
print_philosopher (n, '_', '_');
pthread_mutex_unlock (&fork_mutex[n]);
pthread_mutex_unlock (&fork_mutex[(n + 1) % num_philosophers]);
random_delay ();
}
else
#endif
for (;;)
{
pthread_mutex_lock (&fork_mutex[n]);
print_philosopher (n, '!', '_');
random_delay ();
pthread_mutex_lock (&fork_mutex[(n + 1) % num_philosophers]);
print_philosopher (n, '!', '!');
random_delay ();
print_philosopher (n, '_', '_');
pthread_mutex_unlock (&fork_mutex[n]);
pthread_mutex_unlock (&fork_mutex[(n + 1) % num_philosophers]);
random_delay ();
}
return (void *) 0;
}
int
main (int argc, char **argv)
{
num_philosophers = 5;
{
pthread_mutexattr_t ma;
int i;
pthread_mutexattr_init (&ma);
pthread_mutex_init (&stdout_mutex, &ma);
pthread_mutex_init (&random_mutex, &ma);
fork_mutex = xmalloc (num_philosophers * sizeof (fork_mutex[0]));
for (i = 0; i < num_philosophers; i++)
pthread_mutex_init (&fork_mutex[i], &ma);
pthread_mutexattr_destroy (&ma);
}
{
int i;
int *numbers = xmalloc (num_philosophers * sizeof (*numbers));
pthread_attr_t ta;
philosophers = xmalloc (num_philosophers * sizeof (*philosophers));
pthread_attr_init (&ta);
for (i = 0; i < num_philosophers; i++)
{
numbers[i] = i;
pthread_create (&philosophers[i], &ta, philosopher, &numbers[i]);
}
pthread_attr_destroy (&ta);
}
sleep (1000000);
for (;;)
sleep (1000000);
return 0;
}