我在玩libuv和quickjs(JS引擎)。并利用其核心setTimeout实现了JSRuntime函数。我的JS代码如下所示,这些代码以同步方式运行,而不是按应该以异步方式运行:
console.log("Start");
//this setTimeout will block and , end will be run only once this finish
setTimeout(()=>{
console.log('Timeout has run');
},5000);
console.log("End");该程序的输出是:
Start
Timeout has run
*****This one runs after 5 second*******
End我的Libuv代码就是这样的(不完全是这样,但有点像这样):
int setup_setTimeout(uv_loop_t *loop){
uv_timer_t* timer_req=(uv_timer_t*)malloc(sizeof(uv_timer_t));//without this I get segmentation error, as in my timerCallback it seems t be lost
uv_timer_init(loop, timer_req);
uv_timer_start(timer_req,timerCallback,delay,0);
uv_run(loop, UV_RUN_DEFAULT);
std::cout<<"*****This one runs after 5 second*******"<<std::endl;
}我是一个菜鸟(使用libuv ),因此,如果我遗漏了什么或者运行错误,就会有疑问。因为代码似乎是同步运行的,而不是异步运行的。
发布于 2022-11-07 15:05:15
好吧,所以我找到了解决办法。由于我还没有发布完整的代码,我将尝试解释我如何解决这个问题。
uv_run(loop, UV_RUN_DEFAULT);应该运行在JS脚本evaluation.uv_run,它将开始查找需要处理的事件,它等待的唯一事件就是计时器,因此它将开始运行它。uv_run.之后。
https://stackoverflow.com/questions/74347666
复制相似问题