Ruby Loop error in thread

I have a thread in Ruby. It starts a loop. When this loop reaches sleep (n), it stops and never wakes up. If I run a loop without sleep (n), it starts as an infinite loop.

What happens in the code to stop the thread as expected? How to fix it?

class NewObject
    def initialize
        @a_local_var = 'somaText'
    end

    def my_funk(a_word)
        t = Thread.new(a_word) do |args|
            until false do
                puts a_word
                puts @a_local_var
                sleep 5 #This invokes the Fail
            end
        end
    end
end

if __FILE__ == $0
    s = NewObject.new()
    s.my_funk('theWord')
    d = gets
end

My platform is Windows XP SP3
The ruby โ€‹โ€‹version I installed is 1.8.6

0
source share
1 answer

You are missing a connection.

class NewObject
  def initialize
    @a_local_var = 'somaText'
  end

  def my_funk(a_word)
    t = Thread.new(a_word) do |args|
      until false do
        puts a_word
        puts @a_local_var
        sleep 5 
      end
    end
    t.join # allow this thread to finish before finishing main thread
  end
end

if __FILE__ == $0
  s = NewObject.new()
  s.my_funk('theWord')
  d = gets # now we never get here
end
+1
source

Source: https://habr.com/ru/post/1770001/


All Articles