Synchronization primitives: Mutex and Semaphore (Rendezvous problem) - Article 7

In this article, we shall solve Rendezvous problem.

Rendezvous problem:

Imagine you and your friend plan to go to a trip and decide to meet in Railway station. None of you can proceed before the other has arrived. Once you have arrived, you inform (or signal) your friend via a message or a call then you wait for your friend.

Your friend would also do the same thing if he came first. Similar real life solution can be applied to the threads Rendezvous problem.

Thread 1:

Event A1;
Event B1;

Thread 2:

Event A2;
Event B2;

We have to ensure that T1 and T2 should proceed only after both A1 and A2 are complete. But, anybody can complete A1 or A2 first.

Solution:

Semaphore T1_Arrived = 0;
Semaphore T2_Arrived = 0;

Thread 1:

Event A1;
T1_Arrived.signal(); // Signal T1 has arrived
T2_Arrived.wait(); // Wait for T2
Event B1;

Thread 2:

Event A2;
T2_Arrived.signal(); // Signal T2 has arrived
T1_Arrived.wait(); // Wait for T1
Event B2;

Suppose T2 finishes A2, it signals and waits for T1. Then T1 finishes A1 and signals. Then, they can proceed. This always ensures that A1 and A2 are always complete before B1 or B2.

Comments

Popular posts from this blog

Synchronization primitives: Mutex and Semaphore (Serialization & Mutex problems using Semaphore) - Article 6

Synchronization: Discussion about Mutex and Semaphore - Article 1

Copy constructor in C++ (Part 2)