827 views
4 votes
4 votes
What happens if we run the following program?
int main()
{
int sem;
sem = screate(1); //Semaphore is created and is initialized to 1
fork ();
Wait(sem);
printf(―Gate ―);
Signal(sem);
return 0;
}
(A) Starvation occurs
(B) Deadlock occurs
(C) Both processes enter critical section simultaneously
(D) ―Gate Gate―will be the output

2 Answers

Best answer
3 votes
3 votes

Actually when fork() executed,

child process created, therefore now two processes running from the next point point in the program

The execution of child processes is independent on Parent process therefore interleaved execution may happened

by using semaphore we are restricting that interleaving process therefore either Parent or Child process can enter into CS but at a time only one process.

Therefore Option D is correct.


For observing the difference,

fork();

Wait(sem);

printf(―Gate ―);

Signal(sem);

replace with 

int t=fork();

Wait(sem);

if(t==0)
{
    printf( ― CHILD LINE1 ― );
    printf( ― CHILD LINE2 ― );
}

else
{
    printf( ― PARENT LINE1 ― );
    printf( ― PARENT LINE2 ― );
}

Signal(sem);

then o/p is ONE OF THESE

1) ― PARENT LINE1 ― ― PARENT LINE2 ― ― CHILD LINE1 ―― CHILD LINE2 ― 

2)  ― CHILD LINE1 ―― CHILD LINE2 ― ― PARENT LINE1 ― ― PARENT LINE2 ―

 

what happend if we doesn't use semaphores in the above example?

one of the possible outcome may be 

1)  ― PARENT LINE1 ― ― CHILD LINE1 ― ― CHILD LINE2 ―  ― PARENT LINE2 ―

2)   ― PARENT LINE1 ― ― CHILD LINE1 ― ― PARENT LINE2 ― ― CHILD LINE2 ― 

selected by
1 votes
1 votes
C. as there is a fork so two process will be made parent and child  and they both have a same virtual address and different physical address so they both will be having same sem=1

so after getting exectued wait (Sem) parent prempted and now child come into running state and do wait(Sem) so both the process enter into <CS>

some of you would be having that why both will be having sem=1 as sem is local variable so both parent and child will be having sem=1

Related questions

3 votes
3 votes
0 answers
1
iarnav asked Sep 28, 2018
759 views
Any implementation of a critical section requires the use of an indivisible machine- instruction ,such as test-and-set?Is the above statement True or False?
0 votes
0 votes
1 answer
3
N3314nch41 asked Sep 10, 2023
359 views
How to approach synchronization (specifically semaphore) question, there size are really intimidating and i’m unable to decode the code written? What to do??