On Tue, 11 Jul 2006, Wes G. wrote:
class myClass < Monitor
…
def get_max_value
synchronize { max_value = do_select_to_get_max_value }
max_value
end
This should work just fine - correct?
Just a completely un-Ruby related but Threading in general related
observation.
Think in terms of complete transactions.
So you have the max now.
What are you going to do with it?
Remember, by the time you use it, it may well be wrong. So the
synchronization blocked other threads whilst you were calculating the
max value, but as soon as you have the value, myClass is can be modified
by another thread!
So, do you just want it as a rough indicator of what it was at the time
you
said “get_max_value”?
Or do you need it to be exactly and every time the true max value at the
instant you use it?
In which case you have a bug, a thread race. And it doesn’t matter which
language you are programming in!
So there is two approaches to this…
-
Move the synchronization out to client to synchronize both the
get_max and the use of it.
-
Move the get_max and the use into myClass. This conforms better to
the Law of Demeter or the Tell Don’t Ask principle.
John C. Phone : (64)(3) 358 6639
Tait Electronics Fax : (64)(3) 359 4632
PO Box 1645 Christchurch Email : [email protected]
New Zealand
Carter’s Clarification of Murphy’s Law.
“Things only ever go right so that they may go more spectacularly wrong
later.”
From this principle, all of life and physics may be deduced.