nde_plume@ziplip.com wrote:[color=blue]
> I need a simple multi-thread/process interlock mechanism, that works on
> Windows and Linux. However, they have rather different mechanisms. I
> put together a system that seems to me to work, and be simple, without
> any OS intervention. However, I wanted to ask if anyone saw any
> possible leakage. Here it is:
>
> static volatile int lock = 0; // Variable for lock
>
> void controlledAccess() // Function to control access
> {
> for(;;)
> {
> if(++lock == 1)
> {
> // locked section, free access to protected resource
> --lock;
> break;
> }
> else
> {
> --lock;
> sleep(1000); // Or whatever }
> }
> }
>
> Anyone see a way that two threads can get in the critical section?
>[/color]
Yes, the ++ and -- operations aren't atomic so you can get race
conditions. Two or more threads could see ++lock return 1, e.g.
t1: load reg,lock // reg and lock equal zero
t1: inc reg // reg equals 1
t2: load reg,lock // reg and lock equal zero
t1: store reg,lock // lock equals 1
t2: inc reg // reg equals 1
t2: store reg,lock // lock equals 1
Also you don't have any memory barriers or compiler
optimization barriers to prevent code movement by the
compiler.
And even if the above weren't a problem, you could have
enough threads such that the lock value never went to zero
and cause starvation of the waiting threads. Putting in
a
while (lock != 0) { sleep(1000); }
before the ++lock would help but not prevent the problem
entirely.
Wait loops like that aren't very efficient or responsive.
Lastly, volatile has no meaning with respect to threading.
So using it won't make a threaded program any more or less
correct.
--
Joe Seigh
When you get lemons, you make lemonade.
When you get hardware, you make software.