Code to read: #include <stdio.h> #include <stdlib.h> #include <pthread.h> #inclu
ID: 3700707 • Letter: C
Question
Code to read:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <errno.h>
sem_t s1;
int c=0,x=0;
void *UpdateC1(void *arg)
{
int i;
for(i=0;i<2000000;i++) {
sem_wait(&s1);
c++; x++;
sem_post(&s1);
}
}
void *UpdateC2(void *arg)
{
int i,x=0;
for(i=0;i<4999999;i++) {
sem_wait(&s1);
c++; x++;
sem_post(&s1);
}
}
int main(int argc, char *argv[])
{
int rt,i;
pthread_t t[2];
if(sem_init(&s1, 0, 1)==-1)//Initialize the semaphore;
{
fprintf(stderr,"sem_init failed. errno=%d ",errno);
exit(1);
}
rt=pthread_create( &t[0], NULL, UpdateC1, NULL);
if( rt!=0 )
fprintf(stderr,"Thread %d creation failed: %d ", 0,rt);
rt=pthread_create( &t[1], NULL, UpdateC2, NULL);
if( rt!=0 )
fprintf(stderr,"Thread %d creation failed: %d ", 1,rt);
for(i=0;i<2;i++)
{
rt=pthread_join(t[i], NULL);
if( rt!=0 )
fprintf(stderr,"Wait for thread %d failed: %d ", i,rt);
}
printf (" %c %c ",'a'+(c%2),'a'+(x%2));
return 0;
}
Explanation / Answer
The output of the given code will be :
b a
Explanation:
Suppose there is no any failure as mentioned in the question.
Thre are two threads has been created which will run the subroutine UpdateC1 and UpdateC2.
In Updatec1 subroutine which is run by first thread,we are incrementing the global variables c and x in a for loop which will run 2000000 times.Hence at the end of this subroutine execition the value of global varioable c and x will be 2000000.
In Updatec2 subroutine which is run by second thread,again we are incrementing the global variables c and x in a for loop which will run 4999999 times.But in this case before entering into the loop we have initialized the global variable x to 0.Hence at the end of this subroutine execition the value of global varioable c and x will be 2000000+4999999 and 2000000 respectively.
Since we have used pthread_join() function for both threads that means program will wait there till both threads finish their execution.
Now at the end of this programe we are printing two characters based on the following condition:
1. 'a'+(c%2) -> 'a'+(6999999%2) -> 'a'+1 -> 'b'
2. 'a'+(x%2) -> 'a'+(2000000%2) -> 'a'+0 -> 'a'