• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How many value of x are there?

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If two threads execute the below method increment() concurrently, how many different final values of X are there? You may assume that initially X has value 0.

void increment()
{
int temp = x;
temp = temp + 1;
x = temp;
}

I think it's 2. Can someone please help to verify?

Thanks!
 
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There's the main memory version. Then either or both of the threads may (or may not) have a cached version. We don't know when the threads will run, and we don't know when they'll read the main version or if or when they'll write it. There could be one value, if both threads read 0 from main and write 1 back to it. Or there could be 2 values, 0 and 1 or 1 and 2, where the smaller value is held in main mem and one thread's cache, and the larger value is in the other thread's cache.
 
reply
    Bookmark Topic Watch Topic
  • New Topic