简体   繁体   中英

How do I run a method inside of a class with thread from ruby?

I have a class and attributes there

class Person
  attr_accessor :name
  def say_hello
   puts "person name #{self.name} "
  end
end

Now I want execute the method say_hello but with this thread

queue_thread= []
1..100.times do |number|
  person= Person.new
  person.name= number.to_s
   thread_to_run=Thread.new {person.say_hello}
   queue_thread << thread_to_run
end
queue_thread.map {|thread_current| thread_current.join}

do you have some idea how do it ? I looked and the proplem is than thread is not recognition the vars by instance of object.

the answers correct should be this in console

"person name 1"
"person name 2"
"person name ..."
"person name etc"

The issue with this code is that it fires off multiple threads before calling join - in this time, some of the threads could be called in incorrect order, owing to the asynchronous nature of threads.

One option would be to simply join as soon as the thread is invoked. This will in effect pause the iteration until the thread completes, so you know they'll stay in order:

100.times do |number|
  person= Person.new
  person.name= number.to_s
  Thread.new {person.say_hello}.join
end

Note there is really no point in using a thread here, but it will at least show you can join works.

Another option (which also unnecessarily uses threads) is so delay the thread invocation by storing it as a lambda. This is basically the same thing but allows you to split it up into two iterations:

queue_threads= []
1..100.times do |number|
  person= Person.new
  person.name= number.to_s
  thread_lambda = -> { Thread.new {person.say_hello} }
  queue_threads.push(thread_lambda)
end
queue_threads.map {|thread_lambda| thread_lambda.call.join}

Also note that 1..100.times isn't doing what you think it is. It is the same thing as saying 100.times , so, for example, if you said 99..100.times , the 99 is ignored and it would be 100 iterations and not only 1. If you want to iterate over a range, you could use something like 99..100.each do |i| .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM