问题描述
我想在 Ruby 中制作一个计时器,在用户选择的特定时间后,计时器响起或弹出消息.另外,是否可以让计时器响铃直到用户完成某件事(例如数学题)?
I want to make a timer in Ruby, where after a certain amount of time that the user chooses, the timer rings, or a message pops up. Also, would it be possible to make the timer ring until the user does a certain thing (such as a math problem)?
推荐答案
使用线程:
user_input = Thread.new do
print "Enter something: "
Thread.current[:value] = gets.chomp
end
timer = Thread.new { sleep 3; user_input.kill; puts }
user_input.join
if user_input[:value]
puts "User entered #{user_input[:value]}"
else
puts "Timer expired"
end
在这段代码中运行了三个线程:
Three threads are running in this code:
user_input
线程,它从用户那里获取一个字符串并设置它的value
线程变量timer
线程,它会休眠三秒,然后杀死user_input
线程- 主线程,它产生另外两个线程,然后等待
user_input
线程完成
- The
user_input
thread, which gets a string from the user and sets itsvalue
thread variable - The
timer
thread, which sleeps for three seconds and then kills theuser_input
thread - The main thread, which spawns the other two and then waits for the
user_input
thread to finish
如果没有 timer
线程,代码看起来就像一个提示用户输入然后继续的单线程代码一样工作.两个线程的执行使用#join 进行序列化.主线程通过查看user_input
的value
线程变量来获取用户交互的结果.
Without the timer
thread, the code would appear to work exactly like a single-threaded one that prompts for user input and then continues. The execution of the two threads is serialized using #join. The main thread gets the result of the user interaction by looking at the user_input
's value
thread variable.
timer
线程的添加导致 user_input
线程提前终止(在本例中为 3 秒).发生这种情况时,user_input
线程还没有设置它的 value
线程变量,因此当主线程向它询问这个变量时返回 nil.这是主线程如何确定 user_input
是由于接受用户输入而终止,还是被 timer
线程杀死.
The addition of the timer
thread causes the user_input
thread to terminate early (3 seconds in this case). When this happens, the user_input
thread has not set its value
thread variable, and so returns nil when the main thread interrogates it for this variable. This is how the main thread determines whether user_input
terminated due to accepting input from the user, or being killed by the timer
thread.
这篇关于在 Ruby 中制作计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!