Haris Krajina
Haris Krajina

Reputation: 15286

Extend Thread class

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

Upvotes: 1

Views: 880

Answers (2)

xdazz
xdazz

Reputation: 160883

You don't need to extend the Thread, you could try below instead.

class Foo
  attr_accessor :bar

  def run
    Thread.new do
      puts "Foo thread begins"
      self.bar = "Bar value" # also tried @bar
      sleep(2)
      puts "Foo thread ends"
    end
  end
end

t = Foo.new
t.run

puts "Value: #{t.bar}"
sleep(10)
puts "Value: #{t.bar}"

Upvotes: 1

sawa
sawa

Reputation: 168179

self in your thread refers to the main object, not t. Since the method bar= 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}

Upvotes: 2

Related Questions