简体   繁体   中英

How to create a subclass of Thread in Ruby?

In C/C++, when we create a thread, there is a mechanism to pass some argument to thread execution body. In java, we can subclass the Thread class to allow the thread class include some instance variable. In Ruby, the way to create a thread is:

thread = Thread.new {
   ... code thread execution body
}

After Thread.new , the thread starts to run immediately. All code I have seen use global variables in the thread body. Say we need a mutex lock, the code is:

mutex = Mutex.new
thread = Thread.new {
   ... code thread execution body
   mutex.synchronized {
     ... some code
   }
}

Is it possible to create a subclass of Thread and allow it to have some instance variables? The technical issue I cannot figure out is how to pass code block to subclass and how subclass passes code block to super Thread class.

Broadly, what goal are you trying to accomplish?

You don't need to subclass Thread in Ruby. The block of code you pass to Thread.new will simply be executed in the context of the code that called Thread.new , and will have access to the local variables of the calling method and the instance variables of the instance of the calling class.

class Dog
  def initialize(name)
    @name = name
  end
  def start_barking
    Thread.new do
      10.times do
        puts "Woof! Woof! #{@name}!"
      end
    end
  end
end

If you are looking for thread-local variables, you may use the Thread.current special hash.

10.times do |i|
  Thread.new do
    Thread.current[:i] = i
    sleep 1
    puts Thread.current[:i]
  end
end

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