谷歌面试真题:在单个硬件定时器上实现多个软件定时器

60次阅读
没有评论

“””
We have an embedded environment with a very simple operating system. Part of the facilities provided to us is a single hardware timer.
The goal is to implement multiple timers, each with their own callback, based on this single timer.
The hardware timer can be set with the following function:
void set_hw_timer(int relative_timeout_ms);
After relative_timeout_ms milliseconds have elapsed, the timer triggers a hardware interrupt, which will call the function: void handle_hw_timer();
Only one hardware timer may be pending. Calling set_hw_timer again before the timer has expired will reset the expiration to the new value without triggering the interrupt.
There is also a utility function:
int64_t get_current_time();
which returns the time in milliseconds that have elapsed since boot.
We would like to allow an arbitrary number of timers to be pending. Define the timer structure and implement this function:
void set_timer(struct timer t, int relative_timeout_ms, void (callback)());
Each call to set_timer with a different t parameter should yield a different timer.
The timer structure will be allocated by the caller and passed in, but the caller will not touch the contents of it and you may add any fields you want to it.
The callback function should be called after relative_timeout_ms milliseconds have elapsed. It will be called in interrupt context.
You will also need to implement the body of the handle_hw_timer function.
“””

这道谷歌真题场景是一个极简嵌入式系统:只有一个硬件定时器,但需求是支持任意多个“软件定时器”,每个定时器都有自己的回调函数。系统提供 set_hw_timer 和 get_current_time 这两个底层接口,并在硬件中断中调用 handle_hw_timer。你需要自己定义 timer 结构体,实现 set_timer 来登记一个新的定时任务,并在 handle_hw_timer 中维护数据结构(通常是按到期时间排序的链表或小根堆),确保任何时刻硬件定时器都指向下一次最早到期的任务,到期时在中断上下文中正确触发相应回调。

正文完
 0