I am new to ruby and trying to work around threads
Let's say I have a method which I want to run every x seconds as follows
def say_hello
puts 'hello world'
end
I am trying to run it as follows
Thread.new do
while true do
say_hello
sleep(5)
end
end
But when I run the script, nothing is displayed on the console. What am I missing? Thanks!
In order to create new threads, Ruby provides ::new , ::start , and ::fork . A block must be provided with each of these methods, otherwise a ThreadError will be raised. When subclassing the Thread class, the initialize method of your subclass will be ignored by ::start and ::fork .
Ruby | Thread kill() function Thread#kill() : kill() is a Thread class method which is used to terminates the thread and schedules another thread to be run. Note : The thread object generated in the output depends on the system and pointer value.
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.
Ruby makes it easy to write multi-threaded programs with the Thread class. Ruby threads are a lightweight and efficient way to achieve concurrency in your code.
The main thread is exiting before your thread can run. Use the join method to make the current thread wait for the say_hello
thread to finish executing (though it never will).
t = Thread.new do
while true do
say_hello
sleep(5)
end
end
t.join
You are creating the Thread object, but you are not waiting for it to finish its execution, try with:
Thread.new do
while true do
say_hello
sleep(5)
end
end.join
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