Boost logo

Boost :

From: Eric D Crahen (crahen_at_[hidden])
Date: 2002-05-19 14:36:42


> I don't understand how we get here. T1 doesn't go "do work" unless HIS
> lock is on the circuit breaker keeping it from being closed (and the
> power being turned on)

A thread can get preempted at any time, and another thread can start.
In code, you're going to have to write something along the lines of
this for a worker,

1: if(!switch_on)
2: add_my_padlock();

and something like this for a person turning on the power,

3: if(!switch_has_padlocks())
4: turn_switch_on();

I'll do it with just two threads to simplify.

The switch is off.

T1, executing the first snippet looks at the switch to see if its
on (line 1). T1 is suspended by the scheduler and T2 starts

T2, executing the second snippet looks at the switch to see if
there are padlocks on it (line 3).

T2, sees no locks yet so it turns the power on (line 4).

T1, resumes execution (line 2) - it has already checked the switch
to see if its ok to put a padlock there. So it goes ahead and adds
its lock thinking the power is off. The power was on.

Clearly, this is a race condition. The right way to avoid it is
to serialize access to switch. It may not always happen, it depends on
how the threads are scheduled (and its out of the hands of the
programmer), but it can happen and this will lead to a very serious
problem.

> Filling all of memory with zeros is dangerous also
> setting your priority to as high as possible then doing while(1); is
> dangerous SO??? At least semaphores have utility (which outweighs their
> hazard, IMO). One can easily wrap a mutex around a semaphore, the other
> way is somewhat more problematic

The danger in this case that I'm talking about is that using only
a semaphore leads to a race condition and because of that, it is the
wrong way to approach this problem. Its not so much a matter of
what feeling safe and taking the bet that the race condition doesn't
occur, its a matter of what is correctness by choosing a method that
doesn't contain flaws like a race conditon. Wrapping a mutex around
the semaphore may work, but why even keep the semaphore? It doesn't
have a purpose anymore if you add the mutex.

- Eric
http://www.cse.buffalo.edu/~crahen


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk