异步回调是如何实现的? [英] How is asynchronous callback implemented?

查看:189
本文介绍了异步回调是如何实现的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

怎么办所有的语言实现异步回调?

How do all the languages implements asynchronous callbacks?

例如在C ++中,人们需要有一个监视线程启动的std ::异步。如果在主线程启动,它必须等待回调

For example in C++, one need to have a "monitor thread" to start a std::async. If it is started in main thread, it has to wait for the callback.

std::thread t{[]{std::async(callback_function).get();}}.detach();

v.s。

std::async(callback_function).get(); //Main thread will have to wait

怎么样在JavaScript中的异步回调?在JS回调大量采用......如何V8实施呢?是否V8创造了大量的线程,听取他们,当它得到消息,执行回调?或者它使用一个线程监听所有的回调,并保持清爽?

What about asynchronous callbacks in JavaScript? In JS callbacks are massively used... How does V8 implement them? Does V8 create a lot of threads to listen on them and execute callback when it gets message? Or does it use one thread to listen on all the callbacks and keep refreshing?

例如,

setInterval(function(){},1000);
setInterval(function(){},2000);

是否V8创建2个线程和监控每个回调状态,或者它有一个游泳池的事情来监控所有的回调?

Does V8 create 2 threads and monitor each callback state, or it has a pool thing to monitor all the callbacks?

推荐答案

V8不实现与回调(包括setInterval的)异步函数。引擎只是提供了一种方法来执行JavaScript code。

V8 does not implement asynchronous functions with callbacks (including setInterval). Engine simply provides a way to execute JavaScript code.

作为V8嵌入您可以创建的setInterval JavaScript函数链接到你想要做什么你的本地C ++函数。例如,创建线程或安排一些工作。在这一点上,您有责任调用提供的回调时,它是必要的。一次只能有一个线程可以使用的V8引擎(V8隔离实例)执行code。这意味着,如果一个回调需要从另一个线程称为同步是必需的。 V8提供了锁定机制是你需要这个。

As a V8 embedder you can create setInterval JavaScript function linked to your native C++ function that does what you want. For example, create thread or schedule some job. At this point it is your responsibility to call provided callback when it is necessary. Only one thread at a time can use V8 engine (V8 isolate instance) to execute code. This means synchronization is required if a callback needs to be called from another thread. V8 provides locking mechanism is you need this.

解决这个问题的另一种更常见的方法是创建一个函数队列V8来执行和使用无限队列处理循环在一个线程中执行code。这基本上是一个事件循环。这样,您就不需要使用锁执行,而是使用另一个线程来推回调函数来排队。

Another more common approach to solve this problem is to create a queue of functions for V8 to execute and use infinite queue processing loop to execute code on one thread. This is basically an event loop. This way you don't need to use execution lock, but instead use another thread to push callback function to a queue.

所以,这取决于浏览器/的Node.js /其它嵌入他们如何实现它。

So it depends on a browser/Node.js/other embedder how they implement it.

这篇关于异步回调是如何实现的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆