sawa
sawa

Reputation: 168081

Thread and loop

I am trying to write an equivalent to this code:

Thread.new do loop do
  ...
end end.join

using a class method Thread.loop like this:

Thread.loop do
  ...
end.join

I defined the method as follows:

class Thread
  def self.loop ≺ Thread.new{loop{pr.call}} end
end

and used it like this:

Thread.loop do
  sleep(1)
  puts "foo"
end.join

I expected it to be equivalent to

Thread.new do loop do
  sleep(1)
  puts "foo"
end end.join

but it is not. How can I fix the code?

Is the loop inside Thread.new{} being interpreted as the method loop rather than the keyword? What is the precedence relation between method calls and keywords?

Upvotes: 1

Views: 199

Answers (1)

sawa
sawa

Reputation: 168081

tadman and Stefan let me realize that loop is a private method on Kernel. Considering this, I was able to do it like this:

class Thread
  def self.loop &pr
    Thread.new{Object.instance_exec{loop{pr.call}}}
  end
end

or as suggested by BroiSatse,

class Thread
  def self.loop &pr
    Thread.new{super{pr.call}}
  end
end

and it works as intended.

Upvotes: 2

Related Questions