• Post Reply Bookmark Topic Watch Topic
  • New Topic

Method spins on field  RSS feed

 
Rahul Kakkar
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Say we have the below code:



This method spins in a loop which reads a field. The compiler may legally hoist the read out of the loop, turning the code into an infinite loop. The class should be changed so it uses proper synchronization (including wait and notify calls). So when such waiting is needed, it is better to use proper synchronization constructs like wait and notify, instead of using primitive spin locks.

How would one detect for such cases? When would they occur and how would one know?
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sounds like homework to me. Hopefully, no-one on this site will do your homework for you.

If you demonstrate you've thought about it, and ask some specific questions, you'll find people much more helpful.

If it's not homework, then maybe you don't have to use wait/notify (they're often good, but not the only solution). Maybe you can just declare "lock" as "volatile".
[ December 02, 2005: Message edited by: Peter Chase ]
 
Henry Wong
author
Sheriff
Posts: 23289
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't get it. I know the compiler does "code motion" as part of its optimization, but it doesn't do anything that changes the logic (sans any threading issues).

How will the compiler make this an endless loop?

Henry
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Henry Wong:
I don't get it. I know the compiler does "code motion" as part of its optimization, but it doesn't do anything that changes the logic (sans any threading issues).

How will the compiler make this an endless loop?

Surely it's (homework) about threading issues, otherwise why mention synchronisation and wait/notify?

I guessed that what was meant was that "lock" was a member variable of the class, being monitored by the looping thread, waiting for some other thread to write a non-zero value to it. But, in the absence of "volatile" or any synchronisation, the two threads might be working with separate copies of "lock". The looping thread might not see changes made by the writing thread. That's not quite what the comment implies, but it sounds more likely, don't you think?

(If "lock" was a stack variable, no other thread could change it at all, could it?).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!