等待时如何继续下一个循环?例如:
async def get_message():
# async get message from queue
return message
async process_message(message):
# make some changes on message
return message
async def deal_with_message(message):
# async update some network resource with given message
async def main():
while True:
message = await get_message()
message = await process_message(message)
await deal_with_message(message)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Run Code Online (Sandbox Code Playgroud)
如何使while True循环并发?如果它正在等待deal_with_message,它可以进入下一个循环并运行get_message?
我想我已经找到了解决方案:
async def main():
asyncio.ensure_future(main())
message = await get_message()
message = await process_message(message)
await deal_with_message(message)
loop = asyncio.get_event_loop() …Run Code Online (Sandbox Code Playgroud) 这是简单的测试代码和结果.
import asyncio
async def test():
await asyncio.sleep(1)
if __name__ == '__main__':
asyncio.set_event_loop(None) # Clear the main loop.
loop = asyncio.new_event_loop() # Create a new loop.
loop.run_until_complete(test()) # Run coroutine over the new loop
Run Code Online (Sandbox Code Playgroud)
Traceback (most recent call last):
File "test_test.py", line 11, in <module>
loop.run_until_complete(test())
File "/usr/lib/python3.5/asyncio/base_events.py", line 387, in run_until_complete
return future.result()
File "/usr/lib/python3.5/asyncio/futures.py", line 274, in result
raise self._exception
File "/usr/lib/python3.5/asyncio/tasks.py", line 239, in _step
result = coro.send(None)
File "test_test.py", line 5, in test
await asyncio.sleep(1)
File …Run Code Online (Sandbox Code Playgroud) 我使用 Vert.x v3.5.1。有最简单的代码示例:
vertx.createHttpServer()
.requestHandler(anyRouter::accept)
.listen(8080);
Run Code Online (Sandbox Code Playgroud)
在我的例子中,事件循环组的大小是 16,所以我希望我的请求会影响 16 个线程。服务器已成功启动,但它仅在一个线程中工作。(我使用不同的 tcp-connections 发送请求,所以保持活动不是这里的原因。)
类HttpServerImpl包含httpHandlerMgr并且这个管理器处理一个事件循环池(名为availableWorkers)。在调试期间,我看到这个池只包含一个工人。
使用 Verticle 模型并不能解决问题,仍然没有使用所有线程。
如果我在循环中多次创建服务器,它会有所帮助。因此,我有许多受影响的线程和一台共享服务器。但它看起来像解决方法。
问题是如何创建使用所有可用事件循环线程的 Web 服务器?
下面使用 Verticle 实现
因此,该实现使用了一半的可用线程(8 个线程)。但我希望它使用 16 :)
public static void main(String[] args) throws Exception {
int eventLoopSize = 16;
Vertx vertx = new VertxOptions().setEventLoopPoolSize(eventLoopSize);
for (int i=0;i<eventLoopSize; i++) {
vertx.deployVerticle(new MyServer(vertx), deploymentOptions);
}
}
public class MyServer implements Verticle {
final Vertx vertx;
public MyServer(Vertx vertx) {
this.vertx …Run Code Online (Sandbox Code Playgroud) 在 Flask 应用程序中运行 asyncio 事件循环的最佳方法是什么?
我的 main.py 看起来像这样:
if __name__ == '__main__':
try:
app.run(host='0.0.0.0', port=8000, debug=True)
except:
logging.critical('server: CRASHED: Got exception on main handler')
logging.critical(traceback.format_exc())
raise
Run Code Online (Sandbox Code Playgroud)
要添加异步任务的选项,我需要event_loop在运行之前创建一个app,但即使停止应用程序运行时,后台线程仍然挂起(在调试器中可观察到)
if __name__ == '__main__':
try:
app.event_loop = asyncio.get_event_loop()
app.run(host='0.0.0.0', port=8000, debug=True)
except:
logging.critical('server: CRASHED: Got exception on main handler')
logging.critical(traceback.format_exc())
raise
finally:
app.event_loop.stop()
app.event_loop.run_until_complete(app.event_loop.shutdown_asyncgens())
app.event_loop.close()
Run Code Online (Sandbox Code Playgroud)
并使用以下内容创建异步任务:
def future_callback(fut):
if fut.exception():
logging.error(fut.exception())
def fire_and_forget(func, *args, **kwargs):
if callable(func):
future = app.event_loop.run_in_executor(None, func, *args, **kwargs)
future.add_done_callback(future_callback)
else:
raise TypeError('Task must be …Run Code Online (Sandbox Code Playgroud) 所以我刚刚发现就 C 库而言,libuv是一个相当小的库(与 FFmpeg 相比)。在过去的 6 个小时里,我通读了源代码,以便更深入地了解事件循环。但仍然没有看到“非阻塞”在哪里实现。在代码库中调用某些事件中断信号或诸如此类的东西。
我已经使用 Node.js 超过 8 年了,所以我熟悉如何使用异步非阻塞事件循环,但我从未真正研究过它的实现。
我的问题是双重的:
因此,我们从一个 hello world 示例开始。所有需要的是:
#include <stdio.h>
#include <stdlib.h>
#include <uv.h>
int main() {
uv_loop_t *loop = malloc(sizeof(uv_loop_t));
uv_loop_init(loop); // initialize datastructures.
uv_run(loop, UV_RUN_DEFAULT); // infinite loop as long as queue is full?
uv_loop_close(loop);
free(loop);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我一直在探索的关键功能是uv_run. 该uv_loop_init函数本质上是初始化数据结构,所以我不认为那里有太多花哨的东西。但真正的魔力似乎有发生uv_run,地方。来自 libuv 存储库的一组高级代码片段在此 gist 中,显示了uv_run函数调用的内容。 …
从概念上讲,对于大多数用例来说,只有一个作业队列似乎就足够了。
有多个队列并将它们区分为“微任务”和(宏)“任务”的原因是什么?
我已经创建了简单的演示,让我们开始吧......
应该说我们得用chrome和firefox来对比一下
演示1:
block.addEventListener("click", () => {
block.style.transform = "translateX(500px)";
block.style.transition = "";
block.style.transition = "transform 1s ease-in-out";
block.style.transform = "translateX(100px)";
});Run Code Online (Sandbox Code Playgroud)
.main {
width: 100px;
height: 100px;
background: orange;
}Run Code Online (Sandbox Code Playgroud)
<div id="block" class="main"></div>Run Code Online (Sandbox Code Playgroud)
在这两种浏览器中,我们不会看到任何变化
演示2:
block.addEventListener("click", () => {
block.style.transform = "translateX(500px)";
block.style.transition = "";
requestAnimationFrame(() => {
block.style.transition = "transform 1s ease-in-out";
block.style.transform = "translateX(100px)";
});
});Run Code Online (Sandbox Code Playgroud)
.main {
width: 100px;
height: 100px;
background: orange;
}Run Code Online (Sandbox Code Playgroud)
<div id="block" class="main"></div>Run Code Online (Sandbox Code Playgroud)
在 Chrome 中我们会看到动画,在 Firefox 中我们会看到另一件事。需要提及的是,Firefox 遵循了Jake Archibald in …
我在检查事件循环中的值时尝试使用匹配大小写。然而break,不仅打破了匹配情况,而且也打破了事件循环。
这是代码
while True:
# Some code stuff here
if event == "#PassSign":
# Some code stuff again to check password strength
# Display the password strength
match strength_pass:
case 0:
window["#StatusPassSign"].update("No Password", visible=True)
break
case 1:
window["#StatusPassSign"].update("Password Strength: Low", visible=True)
break
case 2:
window["#StatusPassSign"].update("Password Strength: Medium", visible=True)
break
case 3:
window["#StatusPassSign"].update("Password Strength: High", visible=True)
break
Run Code Online (Sandbox Code Playgroud)
如何在不停止事件循环的情况下中断/停止比赛?
event-loop ×10
python ×5
javascript ×3
aiohttp ×1
asynchronous ×1
c ×1
concurrency ×1
firefox ×1
flask ×1
io ×1
libuv ×1
python-3.5 ×1
python-3.6 ×1
python-3.x ×1
vert.x ×1