假设我有一个方法,其中包含一个计数器,在每个刻度线上将计数器输出到屏幕上。 在程序的其他地方,调用此方法的新版本,因此它们/ all全部运行,具有不同的计数器,并与tick一起更新。用Ruby做到这一点有可能吗?通常创建一个对象的另一个实例就是我要做的事情,但我仍然是Ruby的新手,并且掌握了它。
我将使用示例代码编辑我之后想要实现的内容。我目前在手机上无法访问计算机。
答案 0 :(得分:1)
这里我创建了Counter
的两个实例,两个计数器最初都设置为0.然后我将它们分开3秒 - 每个都在自己的线程中。他们开始打印数字。
class Counter
def initialize
@counter = 0 # initial counter to 0
end
def run
loop do
# wait one second, print the counter and increase it
sleep 1
puts @counter
@counter += 1
end
end
end
threads = []
2.times do
# put each counter in a separate thread
threads << Thread.new do
counter = Counter.new
counter.run
end
sleep 3 # make a pause between launching counters
end
threads.each(&:join)
输出我得到:
0 # first
1 # first
2 # first
0 # second
3 # first
1 # second
4 # first
2 # second
5 # first
这里唯一的技巧是使用Thread
类,否则第二个计数器永远不会开始工作,因为第一个计数器将阻止整个过程。
答案 1 :(得分:1)
您可以使用队列和外部循环,例如:
class Counter
def initialize(start)
@count = start
end
def tick
@count += 1
puts @count
end
end
queue = []
queue << Counter.new(0)
queue << Counter.new(100)
5.times do |i|
puts "--- tick #{i} ---"
queue.each(&:tick)
sleep 1
end
输出:
--- tick 0 ---
1
101
--- tick 1 ---
2
102
--- tick 2 ---
3
103
--- tick 3 ---
4
104
--- tick 4 ---
5
105
在5.times
循环中,tick
被发送到队列中的每个项目。请注意,方法是按计数器添加到队列的顺序调用的,即它们不同时被调用。
答案 2 :(得分:0)
出于您的目的,您可以使用Event循环,Processes或Threads。因为通常情况下Ruby会在方法执行时被阻塞(直到它将返回带有return
的控制权。)
class ThreadCounter
def run
@thread ||= Thread.new do
i = 0
while !@stop do
puts i+=1
sleep(1)
end
@stop = nil
end
end
def stop
@stop = true
@thread && @thread.join
end
end
counter1 = ThreadCounter.new
counter2 = ThreadCounter.new
counter1.run
counter2.run
# wait some time
counter1.stop
counter2.stop