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:
- First, once an instance A of
Thread_A() makes a message
available, A can continue only if it receives a message from
an instance B of
Thread_B().
Similarly, an instance B of
Thread_B() can continue only if
it receives a message from A rather than from any other threads in
group A.
- Second, once an instance A1 of
Thread_A() makes its message
available, we have to make sure that the next instance
A2 of
Thread_A(), which might come
a little later, will not overwrite the existing message before it is
retrieved by an instance of
Thread_B().
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.