如何将异步线与Python中的其他线程一起运行?
我正在尝试与其他线程一起运行异步Run_forever
。但是我只从永远的线程中获得输出,让我认为第二个线程甚至没有启动。
代码 - class.py:code
import asyncio
class Class1:
def __init__(self):
self.loop = asyncio.get_event_loop()
async def _funcClass1(self):
while True:
await asyncio.sleep(5)
print('Hello async/threading world')
def funcClass1(self):
asyncio.ensure_future(self._funcClass1())
self.loop.run_forever()
class Class2:
def __init__(self):
self.loop = asyncio.get_event_loop()
async def _funcClass2(self, name):
print(f'Hello {name}')
def funcClass2(self):
self.loop.run_until_complete(self._funcClass2())
-main.py:
from Classes import Class1, Class2
import threading
import asyncio
class1 = Class1()
class2 = Class2()
if __name__ == "__main__":
t1 = threading.Thread(target=asyncio.run, args=(class1.funcClass1(), ))
t2 = threading.Thread(target=class2.funcClass2, args=('john', ))
t1.start()
t2.start()
t1.join()
t2.join()
输出:
Hello async/threading world
Hello async/threading world
Hello async/threading world
Hello async/threading world
Hello async/threading world
Hello async/threading world
Hello async/threading world
Hello async/threading world
Hello async/threading world
I'm trying to run an async run_forever
together with other threads. But I only get output from the forever thread, making me think that the second thread doesn't even start.
Code - Classes.py:
import asyncio
class Class1:
def __init__(self):
self.loop = asyncio.get_event_loop()
async def _funcClass1(self):
while True:
await asyncio.sleep(5)
print('Hello async/threading world')
def funcClass1(self):
asyncio.ensure_future(self._funcClass1())
self.loop.run_forever()
class Class2:
def __init__(self):
self.loop = asyncio.get_event_loop()
async def _funcClass2(self, name):
print(f'Hello {name}')
def funcClass2(self):
self.loop.run_until_complete(self._funcClass2())
Code - main.py:
from Classes import Class1, Class2
import threading
import asyncio
class1 = Class1()
class2 = Class2()
if __name__ == "__main__":
t1 = threading.Thread(target=asyncio.run, args=(class1.funcClass1(), ))
t2 = threading.Thread(target=class2.funcClass2, args=('john', ))
t1.start()
t2.start()
t1.join()
t2.join()
Output:
Hello async/threading world
Hello async/threading world
Hello async/threading world
Hello async/threading world
Hello async/threading world
Hello async/threading world
Hello async/threading world
Hello async/threading world
Hello async/threading world
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在播放@danangjoyoo的答案之后。我想到了这一点(两个功能都需要以
target = asyncio.run
>):class.py.py
:main.py.py
:After playing around with the answer of @danangjoyoo. I came up with this (both functions need to be executed as
target=asyncio.run
):classes.py
:main.py
:run_forever()
将阻止代码的下一行。运行第二个线程
class.py
main.py.py
之后,请尝试将其放置。run_forever()
will block the next lines of code.try to put it after running the 2nd thread
classes.py
main.py