I am working on a conceptual psuedo-code Semaphore assignment for a class.
I want to know if it is possible to invoke signal() on a semaphore before some process has invoked wait() on it. For instance:
Shared data:
Semaphore x = 0;
Process 1:
wait(x);
print("I'm Process 1, and Process 2 has already printed!");
terminate();
Process 2:
print("I'm Process 2!");
signal(x);
terminate();
The assumption above is that it is not guaranteed which process will be run first, but we want the print statements to execute in the right order (process 2 before process 1). If process 1 starts, it will wait on x. Then process 2 will do its printing, signal x, and allow process 1 to print.
But, if process 2 starts, it will signal x before process 1 has waited on it. The desired outcome would be that x will now be "pre-signaled" for process 1, so that it will skip right over the wait(x) statement. Is this what will actually happen? Or will there be some sort of error because you cannot signal a semaphore that no one is waiting on?
The definitions for wait() and signal() for a semaphore as follows
**wait**(Semaphore S)
{
while S<=0
; //no operation
S--;
}
**signal**(S)
{
S++;
}
In your code semaphore is initialized with zero (Semaphore x = 0), if you try to wait on it, that process gets blocked as you can see from the definition of wait.That means first process never proceed with out calling signal() from second process.
If second process executes first(signal()), the value of the semaphore gets incremented by 1,so that any process waiting on this can proceed with out waiting.(i.e., Process 2 gets wait() it immediately proceeds)