I've lived in the C++ world for years, and I'm just starting out with Ruby. I have a class that I would like to make a thread. In Ruby is it wrong to derive a class from Thread? The examples I see use the concept below.
Thread.new { <some block> }
Would it be wrong to do this?
class MyThread < Thread
def initialize
end
def run
<main loop>
end
Threads are the Ruby implementation for a concurrent programming model. Programs that require multiple threads of execution are a perfect candidate for Ruby's Thread class. For example, we can create a new thread separate from the main thread's execution using ::new .
It's not a common production platform among the RoR community. As a result, Eventhough Rails itself is thread-safe since version 2.2, there isn't yet a good multi-threaded server for it on Windows servers. And you get the best results by running it on *nix servers using multi-process/single-threaded concurrency model.
Calling Thread. join blocks the current (main) thread. However not calling join results in all spawned threads to be killed when the main thread exits.
The Ruby Interpreter is single threaded, which is to say that several of its methods are not thread safe. In the Rails world, this single-thread has mostly been pushed to the server.
I think that this is really a question about domain modeling.
There would be nothing wrong with what you are doing if you want to extend / enhance the way that a thread behaves - for example to add debug or performance output but I don't think that's what you want.
You probably want to model some concept in your domain with active objects. In that case the standard Ruby approach is better because it allows you to achieve this without bending your domain model.
Inheritance really should only be used to model IS_A relationships. The standard ruby code for this neatly wraps up the solution.
To make your object active, have it capture the newly created thread in some method
Class MyClass
...
def run
while work_to_be_done do
some_work
end
end
...
end
threads = []
# start creating active objects by creating an object and assigning
# a thread to each
threads << Thread.new { MyClass.new.run }
threads << Thread.new { MyOtherClass.new.run }
... do more stuff
# now we're done just wait for all objects to finish ....
threads.each { |t| t.join }
# ok, everyone is done, see starships on fire off the shoulder of etc
# time to die ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With