Re: Multi threading - how small is the smallest 'unit' of code
On 1/1/2011 8:13 AM, azserrata wrote:
Say:
//CODE1
(...)
sharedVariable ++;
int i = sharedVariabel;
ITYM `sharedVariable', here and in various other spots.
boolean test=(i==sharedVariable);
(...)
If the code is executed in multiple threads, in a non-synchronized
piece of code, it is possible that 'test' might be FALSE.
Yes. Even worse, `sharedVariable' might have some completely
bizarre value, because each thread does an unsynchronized read-
modify-write on it.
What about these, all non-synchronized.
//CODE2
(...)
int i = (++sharedVariabel);
boolean test=(i==sharedVariable);
Same problem.
Or even:
//CODE3
(...)
int i;
boolean test=((i=(++sharedVariabel))==sharedVariable);
Same problem.
Or the "extreme":
//CODE4
(...)
sharedVariable++;
boolean test=(sharedVariabel==sharedVariable);
Same problem.
Is it possible to guarantee that == is implemented (internally) as a
unique, indivisible, instruction?
The Java language has no such guarantee, since "instruction" is not
part of the definition of Java. The `volatile' qualifier may help with
what you need, but not with what you actually asked.
Or is it possible that other thread might do its increment
(sharedVariable++) somewhere in-between and this thread's 'test' ==
FALSE?
Yes. And without synchronization (or `volatile'), there's no
telling when the other thread's modification might become visible
to this thread.
Thank you for your comments and have a great 2011.
What problem are you trying to solve? There's probably a way
to solve it without taking so many risks.
--
Eric Sosman
esosman@ieee-dot-org.invalid