A Simple Problem

We shall use a very simple problem to illustrate that improper protection is no better that no protection. Suppose we have two groups of threads A and B. Each thread in A (resp., B) runs a thread function Thread_A() (resp., Thread_B()). See the diagram below.

Both Thread_A() and Thread_B() contain an infinite loop in which a thread in one group exchanges an integer message with a thread in the other group. Thus, Thread_A() and Thread_B() have a structure as follows:

There are two important notes:

These two requirements seem complex; but, they are actual very natural. Suppose the employees of two companies A and B exchange business cards. An employee a of company A (i.e., Thread_A()) wants to exchange a business card (i.e., a message) with an employee of company B (i.e., Thread_B()). The first condition states that when a offers his business card to an employee b of company B, a can continue only if he receives b's business card. The second condition means before b can take a's business card, no other employee of company A can interrupt this card-exchange process that may cause b to receive a wrong business card from another A's employee.

The "Exchange msg" is not specified explicitly, because different people may have different implementations. So, how would you implement the "Exchange msg" component? Try it yourself before continue.