• Post Reply Bookmark Topic Watch Topic
  • New Topic

race condition?  RSS feed

 
kelvin cheung
Ranch Hand
Posts: 120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi ,

i wonder why this code will cause "race condition" :



and why must the variables "a" and "b" declared as "static"?

thank you.
 
Stefan Krompass
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

what is the context of your variables a and b? Your code seems to look something like this

Consider you have two threads that are both accessing the foo()-method at the same time. Let a and b initialized to 0. Imagine the first thread entering the method and executing line 4. After incrementing a (i.e. a is set to 1), the thread is put to sleep and the second thread enters the method. Thread 2 increments a in line 4 (sets a to 2) and is put to sleep as well. So the first thread executes lines 5 to 9. Since a is set to 2 and b is set to one (only thread 1 has executed line 5), the result is not what we might expect.

HTH,
Stefan
 
kelvin cheung
Ranch Hand
Posts: 120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi stefan,

so we need to "lock" the method?
we need "synchronization"?

why must the variables declared as static?

thank you very much ^^
 
Stefan Krompass
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

as long as you have two or more threads accessing a method, you need to synchronize it somehow.
For your other question: This might help.

Stefan
 
kelvin cheung
Ranch Hand
Posts: 120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you stefan!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!