2.
With their help, you can organize the expectation of the
fulfillment of some condition. Suppose that one needs to organize the
wait for one thread to complete another (analog of the join
operation). In this case, a semaphore with an initial value of 0
(closed) can be used. The stream that is waiting must perform
a down operation for this semaphore and in order to signal the
completion of the stream, its completion function requires up to
perform the same semaphore. Here is the pseudocode
( this_thread stands for current thread):
Void thread_init ()
{
this _ thread. sem = 0; // At the beginning of the stream execution the
semaphore is exposed
}
void thread _ exit ()
{
up ( this _ thread . sem ); // wake up the pending stream, if any
}
void thread_join (thread_t thread)
{
down (thread.sem); // Waiting for thread to finish
}