Академический Документы
Профессиональный Документы
Культура Документы
Code#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define NUM_PHIL 5
#define MEALS 100
static omp_lock_t chopsticks[NUM_PHIL];
void philosopher()
{
#pragma omp barrier
int id = omp_get_thread_num();
int right_chopstick;
int left_chopstick;
if(id < NUM_PHIL -1)
{
right_chopstick = id;
left_chopstick = id+1;
}
else
{
right_chopstick = 0;
left_chopstick = id;
}
int i;
for(i = 0; i < MEALS; i++)
{
omp_set_lock(&chopsticks[left_chopstick]);
omp_set_lock(&chopsticks[right_chopstick]);
printf("philosopher %d is eating\n", id);
usleep(100);
omp_unset_lock(&chopsticks[left_chopstick]);
omp_unset_lock(&chopsticks[right_chopstick]);
}
}
int main(int argc, char ** argv)
{
int i;
for(i = 0; i < NUM_PHIL; i++)
omp_init_lock(&chopsticks[i]);
#pragma omp parallel num_threads(NUM_PHIL)
{
philosopher();
}
for(i = 0; i < NUM_PHIL; i++)
omp_destroy_lock(&chopsticks[i]);
return 0;
}
omp_set_lock(&chopsticks[left_chopstick]);
omp_set_lock(&chopsticks[right_chopstick]);
RELEASING CHOPSTICKS:
omp_unset_lock(&chopsticks[left_chopstick]);
omp_unset_lock(&chopsticks[right_chopstick]);
4. Initialize locks:
for(i = 0; i < NUM_PHIL; i++)
omp_init_lock(&chopsticks[i]);
OUTPUT:
The following screenshot describes the working of the program
when: a) When each philosopher is eating twice.
b) When each philosopher is eating once.
(Hence this program can be executed even for when each
philosopher eats n times.)