在不同的线程中运行coroutine循环

时间:2017-11-20 01:13:11

标签: python multithreading python-multithreading python-asyncio

我想在两个帖子中分四次调用streamSimulation

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

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()

1 个答案:

答案 0 :(得分:1)

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

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

单循环的原因是:它是 IO-bound ,循环执行的代码永远不会阻塞,除非等待IO / timer事件< / em>的

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

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