I found a C/Linux exercise in a book, and I propose a code as a solution, please feel free to correct it.
Here is the exercise :
Taking into consideration the following dependency graph, which express dependency relations between 4 tasks of a program :
We want to create 4 processes (S1 to S4) which will be executed in parallel in order to automate the dependency graph above. Each process Si will be based on the model 1 below :
Propose a solution and clearly justify it.
Here is the code :
sem_t free;
sem_t busy;
static int x1 = 1, x2 = 1, x3 = 1;
void *s1(void *z)
{
float b = 0;
sem_wait(&busy);
b = (54 * 91) - 43;
printf(" (54 * 91) - 43 = %f # Task 1 completed.\n\n", b);
x1 = 0;
sem_post(&free);
}
void *s2(void *z)
{
float c;
sem_wait(&busy);
c = (30 + 71) - 63;
printf(" (30 + 71) - 63 = %f # Task 2 completed.\n\n", c);
x2 = 0;
sem_post(&free);
}
void *s3(void *z)
{
float d;
sem_wait(&busy);
d = (65 - 40) * 58;
printf(" (65 - 40) * 58 = %f # Task 3 completed.\n\n", d);
x3 = 0;
sem_post(&free);
}
void *s4(void *z)
{
float e;
sem_wait(&busy);
e = 81 - (35 * 46);
printf(" 81 - (35 * 46) = %f # Task 4 completed.\n\n", e);
sem_post(&free);
}
int main(void)
{
pthread_t tr;
sem_init(&free, 0, 5);
sem_init(&busy, 0, 0);
pthread_create(&tr, NULL, s1, NULL);
if (x1 == 0)
{
pthread_create(&tr, NULL, s2, NULL);
pthread_create(&tr, NULL, s3, NULL);
}
if ((x1 == 0) && (x3 == 0))
{
pthread_create(&tr, NULL, s4, NULL);
}
pthread_exit(NULL);
}