2012-01-23 111 views
1

这是一个非常简单的问题。简单的红宝石对象顺序

def func1 
    t2=Thread 
    while true 
     # if t2.alive?     
     # puts "GUI is running" 
     # end 
     puts Thread.t2.stop? 
     puts "func1 at: #{Time.now}" 
     sleep(1) 
    end 
end 

t1=Thread.new{func1()} 
t2=Thread.new{TheGUI()} 
t1.join 
t2.join 

t2仅在代码中稍后声明,因此在尝试运行时出现错误。 错误是'未定义的局部变量或方法't2''

如何解决这个问题,而不需要重新排序我的代码?

感谢

回答

2

您的片段是非常小的,所以这是很难说,如果你的代码是在顶层或一类。

如果t2应该是一个全局变量,请注意Ruby prefixes global variables with a $$t2

如果t2应该是班级成员,请注意Ruby prefixes member variables with a @@t2

更新

你更新的代码正在为名为t2Thread类的别名。检查此输出:

$ irb 
irb(main):001:0> t2=Thread 
=> Thread 
irb(main):002:0> t2 
=> Thread 
irb(main):003:0> t2.methods() 
=> ["private_class_method", "inspect", "name", "stop", "tap", "clone", "public_methods", "__send__", 
... 
irb(main):004:0> Thread.methods() 
=> ["private_class_method", "inspect", "name", "stop", "tap", "clone", "public_methods", "__send__", 

此外,该t2别名仅在力在func1函数定义的范围。

修改你的代码最简单的方法是可能改变func1取一个参数:

def func1(second_thread) 
    while second_thread.alive? 
    puts "GUI is running" 
    sleep 1 
    end 
end 

t2 = Thread.new {TheGUI()} 
# pass the parameter to the function here 
t1 = Thread.new(t2) { |thread| func1(thread) } 
t1.join() 
t2.join() 
+0

我更新的代码。谢谢 –

+0

哇,非常感谢! –