From: Wes Gamble Date: 2006-07-11T06:10:59+09:00 Subject: Re: Best way to synchronize access to a method? Simon Kræ—¦ger wrote: > Wes Gamble wrote: >>> >>> Thanks, >> Thanks, >> Wes > > You have several problems in your code you may want to look at before > thinking > about Threads: > > * myClass has to be spelled MyClass (see Constants in Ruby) > > * get_max_value isn't a class method (use self.get_max_value if you want > such) > > * max_value is only defined inside the block, so you get > "undefined local variable or method `max_value' for MyClass:Class" > > * if you define it as class method the interpreter will show you > "undefined method `synchronize' for MyClass:Class" because synchronize > isn't a class method > > * most of the time when the documentation is saying "it is essential > to..." > it is there for a reason > > I don't want to be harsh, but it would be nice to let the interpreter > find > the obvious bugs it is able to find. > > maybe that is what you want: > > require 'thread' > > class MyClass > @@mutex = Mutex.new > > def self.do_select_to_get_max_value; > 42 > end > > def self.get_max_value > @@mutex.synchronize do > return do_select_to_get_max_value > end > end > end > > p MyClass::get_max_value > > cheers > > Simon Simon, Thanks for the feedback. The code below appears to work. Do you agree that the code will be sychronized on the class object itself? ===================== require 'monitor' class Job < ActiveRecord::Base self.extend(MonitorMixin) .... public def self.get_next_job_number max_value = nil synchronize { max_value = self.find(:first, :select => 'MAX(AbsJobNumber) AS max').max } max_value.to_i + 1 end end -- Posted via http://www.ruby-forum.com/.