With Ruby 1.8.7 I am trying to extend Thread class here is snippet
class Foo < Thread
attr_accessor :bar
end
t = Foo.new do
puts "Foo thread begins"
self.bar = "Bar value" # also tried @bar
sleep(2)
puts "Foo thread ends"
end
puts "Value: #{t.bar}"
sleep(10)
puts "Value: #{t.bar}"
Output is
>Foo thread begins
>Value:
>Foo thread ends
>Value:
Why am I not able to see :bar attribute for Foo class? Since this is probably not made to work this way, how do I pass value from my newly created Thread to main thread?
Thank you
selfin your thread refers to the main object, nott. Since the methodbar=is not defined on the main object, it throws an error, which is not sent to the main thread.There are several ways you can access the thread:
1)
Foo.new{p Foo.current}2)
Foo.new{|foo| p foo}3)
foo = Foo.new{p foo}