Heartbeats
Are you working in Ruby and need to do some asynchronous work? Like, you're waiting for an input but also want your program to, say, be doing other calculations on the side, or to stop waiting if your user is too slow?
One of the first programs I made this year was an emulation of the game Set, which a certain element of speed to it - players try to make sets before each other (or before the computer does, in this version). Here was my solution for allowing the terminal to continue displaying available cards while *also* waiting for the player to input a set while *also* putting a clock on the player's actions and letting the computer jump in with its move when time was up:
This method works...but it's also got some downsides. Namely, that rescue statement deliberately introduces an error if it times out. In a simple terminal application like mine, this wasn't a problem - that's basically what I wanted it to do. However, this can cause lots of problems in other contexts, like running a web app. Basically, Timeout is a bomb that will remove infected tissue when sometimes a scalpel is all that is needed.
Enter Heartbeats.
Basically, instead of telling Ruby to do two things at once, which it's bad at, you can tell Ruby to do things really fast at the same time (which it's good at). Here's how to do it:
1. Tell your machine to be doing Task A (say, waiting for a player's input) with a timer loop.
2. Add Task B to your loop (say, calculating a new game state or just counting the overall time that's been spent on Task A).
3. Add a check at the end of your loop for Task A and add a check for Task B.
Your Ruby program will now do two things, indistinguishably from the human eye, at the same time.
Tada!
Here's a link to a white paper from Microsoft about the creation of this idea in network computer and its advantages if you want some more advanced reading.
Comments
Post a Comment