Originally posted by Tim Holmes:
This may seem like a dumb question, but i am trying to understand threading better. If that is the case that "someVariable" is unique to each thread and also that methods are unique to each thread, then what is the point in synchronizing?
Correct, "local" variables do not need any "synchronizing".
The whole point of synchronizing is so that a variable or method does not get accessed by more than one thread at any point in time, right?
If you create in single instance of an object, lets say "Car", with the method "changeToNextGear()"
Then you create multiple threads calling the method changeToNextGear().
new Thread().start()->run.. => changeGear()
new Thread().start()->run.. => changeGear()
new Thread().start()->run.. => changeGear()
The thread 1
- reads gear=0
- set gear+1 = 1
- activate gear=1.
The thread 2:
- reads gear=1
- set gear+1 = 2
//In parallel, Thread 3 now becomes the active thread and execute the method
The thread 3:
- reads gear=2 (remember, thread2 just changed it)
- set gear+1=3
- activate gear=3 // your car just went from 1st to 3rd
So the only time that would happen would be when a method or variable is "static" at which point there would be only one copy to work with and you would need to restrict it to one thread at a time. Right??[/qb]
Anything else than local variables. Actually, not just variables, if you need to perform actions on a resource (a file), even if you are using local variable, you need to be aware that at anytime between 2 lines of code, another thread could be changing things.
Regards,
Alex
[ January 23, 2008: Message edited by: Alex Belisle Turcot ]