Consider the following multi-threaded program. Discuss with adequate explanation what you expect to see when this program is run.
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
sem_t s;
volatile int count = 97;
int A[3];
void f() {
sem_wait(&s);
count++;
sem_post(&s);
while (count != 100);
sem_wait(&s);
count--;
sem_post(&s);
}
void *work(void *param) {
int i, tid = *(int*)param;
for (i = 0; i < 3; i++) {
A[tid]++;
f();
}
return NULL;
}
int main() {
pthread_t threads[3];
int i, tid[3], sum = 0;
A[0] = 0;
A[1] = 1;
A[2] = 2;
sem_init(&s, 0, 1);
for (i = 0; i < 3; i++) {
tid[i] = i;
pthread_create(&threads[i], NULL, work, &tid[i]);
}
for (i = 0; i < 3; i++) {
pthread_join(threads[i], NULL);
}
for (i = 0; i < 3; i++) {
sum += A[i];
}
printf("SUM=%d\n", sum);
return 0;
}