Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Threads and a local variable

 
Allen Bandela
Ranch Hand
Posts: 128
Eclipse IDE MS IE Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not sure if this is even a sensible question.
I was wondering if the following code can ever print a 1.

And the output on several runs has always been:
0
0
0
0
0

My aim in this program is to let all the threads run line 1 and sleep. After that, I hoped to see a thread modify count and sleep. Now, the former scenario having occured, all the threads must print a value greater than 0.
Am I right in my thinking? This problem is not a real-world development problem, its just a thing that came into my mind.
[ November 17, 2006: Message edited by: Allen Sylvester ]
 
Purushoth Thambu
Ranch Hand
Posts: 425
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Each thread has it's own local copy. Local objects are allocated in thread's stack not in heap. So any modification you make on local member of one thread will not be visible to other thread. You need common shared object if you want threads to interact.

What you are trying to accomplish is this

[ November 17, 2006: Message edited by: Purushothaman Thambu ]
 
Sam Codean
Ranch Hand
Posts: 194
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
try putting these instead and you will see what you want to



Your count was declared in the function stack which is not shared between instances you need to have it declared shared or static
 
Allen Bandela
Ranch Hand
Posts: 128
Eclipse IDE MS IE Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys. I was'nt sure local variables were not shared by threads..was'nt even thinking in terms of different call stack for each thread... geez..thanks again.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic