[ prev | next | up ]

Where is the race condition?

[from your friendly TA]

> Where is the race in the example code from Franco's web page?

Reduce it to a simple case of two gangsters. G1 and G2.

Call the semaphore 'sem'
sem starts off as 0.

The parent is sleeping waiting for sem to reach 2. semop(-2).

G1 signals. sem is '1'
G1 is blocked waiting for sem to reach '0'

context switch occurs:
G2 signals. sem is '2'
G2 is blocked waiting for sem to reach '0'

context switch:
the parent (strobe) waits semop(-2). sem is now '0'

context switch to G1:

Here lies the nasty race.

If G1 runs for just a bit longer than G2 then it will pass the wait and
signal the semaphore again in the next iteration of the loop.

sem is now '1' and both G1 and G2 are waiting for it to reach 0. The
parent is waiting for it to reach '2'. We're stuck in between, a classic
example of deadlock.

The example is fairly simple but illustrates again how a subtle race can
creep in and sometimes break code that otherwise works. The only ways to
detect races are
a) Think, think, think and then think again
b) Stress test

It's up to you guys to come up with a way to synchronize your 6 processes.

Remember it can be done (sans races) with as little as 2 semaphores, 1 is 
not enough.