> : It doesn't work. There's no guarantee that two or more processes won't
> : check the 'read' flag simultaneously such that both think they are "ok."
> But there ain't no 'simultaneously' things...
> Well, maybe in a multi-processor environment this may happen...
Actually, it wouldn't happen simultaneously, it would happen like this:
Task 1 Task 2
Gee, I think I'll read
the semaphore flag.
Hmm... It seems to be clear
>>>-----------> Context switch >>>--------->
Gee I think I'll read the
semaphore flag.
Hmm... It seems to be clear.
Now I think I'll set it.
Now on to some semaphore
related stuff....
<-----------<<< Context switch <---------<<<
Gee, the flag was clear, so
I think I'll set it.
Now I'll do my semaphore
related stuff....
>>>-----------> Context switch >>>--------->
Ok. I'm done with the semaphore
stuff. I'll clear the flag.
(other junk)
<-----------<<< Context switch <---------<<<
Ok. Time to clear the flag.
Basically, you have to ensure that a context switch doesn't occur between
the time that a process tests and sets the flag. If it does, you have
no guarantee that another process won't test the flag immediately after
you test the flag.
There are ways to get around this without an atomic test-and-set instruction
in your machine's instruction set. The Amiga, for example, has two functions, Forbid()
and Permit(), which disable and enable (respectively) context switches.
So, you do something like this:
Forbid();
localflag = the_flag;
the_flag = 1;
Permit();
if (!localflag)
{
/* the_flag was unset */
whatever ();
}
else
{
/* the_flag was set */
wait_around_or_something();
}
If you don't have an atomic test-and-set instruction, though, I think
it can be done with an addition (provided the addition instruction
is atomic). The semaphore flag is an integer where zero represents
clear. To test/set the flag, you add one to it, and the check its
value. If the value is one, then you were the only person to add to
it. If the value is more than one, the semaphore is already in use.
If it's in use, you subtract one from it.
Adios,
Logan
--
He was desperate then he found the open gate ___///__
Guards were standing there all day ______________/___ I do not
Something made them look the other way __________/___ speak for
-Elim Hall, "Testimony" ___________________/___ Pencom