Class A
def foo
do s.t
end
end
class B
def initialize
@bar = Thread::ne开发者_JS百科w{
A::new
}
#Here I want to call A.foo in the thread @bar
end
end
bar = B::new
I want to start a new thread with the class A. How can I call the method foo from class B?
I think you are confused about your problem. Firstly, you say
I want to start a new thread with the class A
but it is unclear what you mean by that. You can't start a thread 'with' a class. Secondly, you say
Here I want to call A.foo in the thread @bar
but you're not inside the block that is being executed in the new Thread at that point. Even if you were, there is no class method 'foo' of class A, so A.foo
will only result in a NoMethodError
. Then you say you want to
call the method foo from class B?
even though the comment about calling foo is in an instance of B.
So, I'm assuming you mean the following:
Class A
def foo
end
end
class B
def initialize
@bar = Thread::new{
a = A::new
}
# Here I want to call a.foo
end
end
bar = B::new
Now, in that case, your problem is that the new instance of A
that you created is local to the block that the thread @bar executes. It is not an instance variable of the Thread instance that you created and you cannot access any method of that instance. However, what you can do is create that instance beforehand and share it with the thread:
class B
def initialize
a = A.new
@bar = Thread::new {
do_stuff_with a
}
a.foo
end
This will work just fine. Of course, you run into concurrency hell and all problems generally associated with using threads. Beware.
精彩评论