This is psuedocode for task synchronization using a semaphore.
The operation involves a security check between transferring data.
Begin_Security_Check=create_semaphore(0);
Security_Check_Done=create_semaphore(0);
Task Security_Check
{
while(true)
{
wait_semaphore(Begin_Security_Check);
(*actions check data*)
signal_semaphore(Security_Check_Done);
}
}
Task Download_Data;
{
(*actions to download data from WAN to router buffer*)
signal_semaphore(Begin_Security_Check);
wait_semaphore(Security_Check_Done);
(*actions to download data from router buffer to LAN*)
}
In the notes I’m reading :
s= create_semaphore(v);
Where v=0 or 1
wait_semaphore(s);
If s=1 then set s=0 and allow the calling task to proceed, otherwise suspend the calling task.
signal_semaphore(s);
If there is no task waiting for semaphore sthen set s=1 otherwise resume any task that is waiting on semaphore s.
But this means wait_semaphore(Begin_Security_Check); has a value of 0 because Begin_Security_Check=create_semaphore(0);, right? This means it should suspend the calling task ?
The first two definitions have create_semaphore(0); — that means they’re both the same?
I’m really confused, can someone please go step by step and explain how this pseudo code is running?
Initially we create two semaphores, each with a value of 0.
Now I’m guessing these two
Tasksare somehow started on separate threads – in particular,Task Security_Checkseems to loop forever, so it must be sitting in its own thread waiting for work. When it callswait_semaphore(Begin_Security_Check);, it will pause until someone signalsBegin_Security_Check.Now someone calls
Download_Data. It does whatever it needs to do to download the data, and then signals the semaphoreBegin_Security_Check. This wakes up theSecurity_Checkthread, which then proceeds to do whatever it needs to do and signals theSecurity_Check_Donesemaphore. Meanwhile, the downloading thread will have gone on towait_semaphore(Security_Check_Done);, causing it to pause until theTask Security_Checksignals that semaphore. So it will not proceed until the security check is finished.