K
Kfir Lavi
Hi,
I have singleton class I want to observe with another class. The
problem is that the singleton class will create the instance of the
class that wants to observe it.
Here is an example:
require 'singleton'
require 'observer'
class A
include Singleton
include Observable
def initialize
B.new
sleep 10
end
end
class B
def initialize
# register for A updates
A.instance.add_observer(self) # will fail, because it waits for A
end
end
A.instance
You need to stop the program with Control-C and you get:
^C/usr/lib/ruby/1.8/singleton.rb:149:in `sleep': Interrupt
from /usr/lib/ruby/1.8/singleton.rb:149:in `_instantiate?'
from /usr/lib/ruby/1.8/singleton.rb:105:in `instance'
from c.rb:21:in `initialize'
from c.rb:10:in `new'
from c.rb:10:in `initialize'
from /usr/lib/ruby/1.8/singleton.rb:94:in `new'
from /usr/lib/ruby/1.8/singleton.rb:94:in `instance'
from c.rb:25
Command terminated
The problem is that A didn't finish initializing, and B in order to
add_observer waits for A to finish initialize. So both A and B
sleeping waiting for each other.
I thought to solve it by creating a thread that will wait for A to
finish initialize.
Something like this:
Thread.new(self) do |me|
while A.instance.not_initialize? do
sleep 2
end
A.instance.add_observer(self)
end
But how do I monitor if A finished initialize?
Also, is there a better way of doing this? Idiom?
Thanks,
Kfir
I have singleton class I want to observe with another class. The
problem is that the singleton class will create the instance of the
class that wants to observe it.
Here is an example:
require 'singleton'
require 'observer'
class A
include Singleton
include Observable
def initialize
B.new
sleep 10
end
end
class B
def initialize
# register for A updates
A.instance.add_observer(self) # will fail, because it waits for A
end
end
A.instance
You need to stop the program with Control-C and you get:
^C/usr/lib/ruby/1.8/singleton.rb:149:in `sleep': Interrupt
from /usr/lib/ruby/1.8/singleton.rb:149:in `_instantiate?'
from /usr/lib/ruby/1.8/singleton.rb:105:in `instance'
from c.rb:21:in `initialize'
from c.rb:10:in `new'
from c.rb:10:in `initialize'
from /usr/lib/ruby/1.8/singleton.rb:94:in `new'
from /usr/lib/ruby/1.8/singleton.rb:94:in `instance'
from c.rb:25
Command terminated
The problem is that A didn't finish initializing, and B in order to
add_observer waits for A to finish initialize. So both A and B
sleeping waiting for each other.
I thought to solve it by creating a thread that will wait for A to
finish initialize.
Something like this:
Thread.new(self) do |me|
while A.instance.not_initialize? do
sleep 2
end
A.instance.add_observer(self)
end
But how do I monitor if A finished initialize?
Also, is there a better way of doing this? Idiom?
Thanks,
Kfir