209 views
1 1 vote
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;
}

Please log in or register to answer this question.

Position:
Show:

Related questions

0 0 votes
0 0 answers
237
237 views
RUPALI_SHAHAPURE asked Nov 15, 2024
237 views
Four processes execute a critical section that increments the shared variable count by one i.e., the critical section is count++. Unfortunately, the mutual exclusion algo...
1 1 vote
1 1 answer
322
322 views
soudipta_dutta asked Sep 19, 2025
322 views
TRUE OR FALSEThere exists a unique feature map $\phi_{\text{lin}}: \mathbb{R}^2 \to \mathbb{R}^D$ for the linear kernel such that \[\langle \phi_{\text{lin}}(\mathbf{x}),...
3 3 votes
1 1 answer
2.2k
2.2k views
Abhishek95 asked Mar 28, 2017
2,159 views
Greetings to all, and congrats to everyone who succeeded. I'm very much confused about my options, and I need some guidance from some of you experienced people.First of a...
2 2 votes
0 0 answers
573
573 views
RUPALI_SHAHAPURE asked Nov 15, 2024
573 views
Consider a counting semaphore s1 initialized to two. The binary semaphore s2 is initialized to one. There are three processes executing the following code segment concurr...