Ideas for throttling update frequency
Here is my situation, I have a external program that sends me data every 30 or so ms. That data is merged to a ref.
At this point I have,
(def state (ref {})
a seperate future reads and merges packets to this ref.
Now I have my state machine, that is making decisions and sending back control commands. Basically each state has the following structure,
(while (some-thing-happening)
(calc-stuf开发者_如何学Gof)
(send-correction))
Here is my problem, if I receive 100 packets/sec there is no point in sending 200 commands/sec. So I would like to come up with a scheme that will throttle the update rate. I can not sleep for some ms cause update rate is not deterministic. How would you structure this?
First, you need a measure to prevent work while no data is arriving. You can accomplish that by
- Receiving a callback when packets arrive, which advances your state machine. Use that, if your IO API has callbacks.
- Blocking in
some-thing-happening
until a packet arrives. Use that if the API allows it and there is no callback. - Write incoming packets into a BlockingQueue and read from that in your state machine. This emulates 2.
Second, you might want to model your state as an agent:
(def state (agent {}))
This way, you can say
(defn update-state [state data]
; e.g.
(merge state data))
;; in the state machine
(send state correct data)
which updates your state in a separate thread.
You can even send packages to the agent directly from where you read them and implement the state machine in update-state
.
Make a call to the state machine function when you alter the ref. This way you can send commands at the same rate as your data changes.
Or, use another ref as flag and set it to true when you update the data, add the flag as a condition to the while loop. And reset it to false after the update.
精彩评论