Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby - start a thread

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!

like image 648
dopplesoldner Avatar asked Oct 21 '13 15:10

dopplesoldner


People also ask

How do you start a thread in Ruby?

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 .

How do you end a thread in Ruby?

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.

Is Ruby multithreaded or single threaded?

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.

Does Ruby have real threads?

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.


2 Answers

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
like image 84
axblount Avatar answered Oct 06 '22 00:10

axblount


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
like image 24
rorra Avatar answered Oct 06 '22 00:10

rorra