Xinu下实现一个函数,将目标函数func延时多少秒后执行,但该函数本身不会像sleep()那样阻塞当前进程
时间: 2023-05-23 19:05:29 浏览: 52
A:
在Xinu下可以使用定时器来实现目标函数延时执行的功能,其流程如下:
1. 创建一个定时器,设置其触发时间为延时的秒数。
2. 将目标函数的指针和参数传递给回调函数(callback)。
3. 在回调函数中执行目标函数。
需要注意的是,回调函数中不能直接执行目标函数,因为回调函数的执行是在定时器的中断处理程序中完成的,而这个中断处理程序是不允许直接执行目标函数的。因此,需要将目标函数的指针和参数保存下来,在回调函数中执行。
以下是一个实现示例:
```
#include <xinu.h>
static void delayed_callback(uint32 func_ptr, uint32 arg)
{
void (*func)(uint32 arg) = (void (*)(uint32 arg))func_ptr;
func(arg);
}
void delayed_execute(void (*func)(uint32 arg), uint32 arg, uint32 delay)
{
tid_typ tid = newtid();
struct timer *tmr = tmr_create((void (*)(uint32))delayed_callback, delay * 1000, 1, (uint32)func, arg);
if (tmr == NULL) {
kprintf("failed to create timer\n");
return;
}
tmr_start(tmr);
kprintf("timer started\n");
}
```
使用方法如下:
```
void my_func(uint32 arg)
{
kprintf("my_func called with arg=%d\n", arg);
}
int main(int argc, char **argv)
{
delayed_execute(my_func, 42, 5);
// other code...
return 0;
}
```
以上代码会在延时5秒后调用my_func函数,并输出"my_func called with arg=42"。注意,此过程不会阻塞当前进程的执行。