运行 不同线程中的协程循环
Run coroutine loop in different thread
我想在 2 个线程中调用 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()
您的想法与异步方式冲突,抱歉。
通常你需要一个单事件循环在主线程和线程池执行 CPU 绑定 任务。
单循环的原因是:它是IO-bound,循环执行的代码不应该阻塞 除了等待 IO/timer 个事件 .
这意味着两个循环不会提高性能:它们都被内核 IO 子系统阻塞。
唯一的例外是让两个不同的事件循环一起工作,例如asyncio 和 Qt(但对于这种特殊情况,有 qualmash 项目)。
我想在 2 个线程中调用 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()
您的想法与异步方式冲突,抱歉。
通常你需要一个单事件循环在主线程和线程池执行 CPU 绑定 任务。
单循环的原因是:它是IO-bound,循环执行的代码不应该阻塞 除了等待 IO/timer 个事件 .
这意味着两个循环不会提高性能:它们都被内核 IO 子系统阻塞。
唯一的例外是让两个不同的事件循环一起工作,例如asyncio 和 Qt(但对于这种特殊情况,有 qualmash 项目)。