在不同线程中运行协程循环

阿恩

我想streamSimulation在 2 个线程之间调用四次。

如何创建第二个循环,创建第二个线程并在该线程中执行循环?

import asyncio
import functools
from concurrent.futures import ThreadPoolExecutor


async def streamSimulation(p1,p2,p3,p4):
    print("Stream init")
    while True:
        await asyncio.sleep(2)
        print("Stream Simulation")
        print("Params: " + p1 + p2 + p3 + p4)
        doSomething()

def doSomething():
    print("Did something")

def main():
    loop = asyncio.get_event_loop()
    #Supposed to run in first thread
    asyncio.ensure_future(streamSimulation("P1","P2","P3","P4"))
    asyncio.ensure_future(streamSimulation("A1","A2","A3","A4"))
    #Supposed to run in second thread
    asyncio.ensure_future(streamSimulation("Q1","Q2","Q3","Q4"))
    asyncio.ensure_future(streamSimulation("B1","B2","B3","B4"))
    loop.run_forever()

main()
安德鲁·斯维特洛夫

你的想法与异步方式冲突,抱歉。

通常,您需要线程和线程池中使用单个事件循环来执行CPU 绑定任务。

单循环的原因是:它是IO-bound 的,循环执行的代码除了等待 IO/timer events 之外永远不应该阻塞

这意味着两个循环不会提高性能:它们都被内核 IO 子系统阻塞。

唯一的例外是将两个不同的事件循环一起工作,例如 asyncio 和 Qt(但对于这种特殊情况,有qualmash项目)。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章