【发布时间】:2020-10-12 10:00:25
【问题描述】:
我有一个“服务器”线程,它应该监听来自其他服务器线程的调用/事件,同时执行一些其他代码。最近我在 Node.js 上工作了很多,所以我认为使用 async/await 创建一个事件循环会很好,我可以在其中等待其他线程加入事件循环并在它们最终加入时处理它们的响应。
为了测试这个想法,我在 Python 3.5 中编写了以下测试脚本:
# http://stackabuse.com/python-async-await-tutorial/
# Testing out Python's asynchronous features
import asyncio
from time import sleep
import threading
from threading import Thread
import random
class MyThread(Thread):
def __init__(self, message):
Thread.__init__(self)
self._message = message
def run(self):
self._return = self._message + " oli viesti"
a = random.randint(1, 5)
print("Sleep for ", a)
sleep(a)
print("Thread exiting...")
def join(self):
Thread.join(self)
return self._return
async def send(message):
t = MyThread(message) # daemon = True
t.start()
print("asd")
return t.join()
async def sendmsg(msg):
response = await send(msg)
print("response is ", response)
if __name__ == "__main__":
# Initiate a new thread and pass in keyword argument dictionary as parameters
loop = asyncio.get_event_loop()
tasks = [
asyncio.ensure_future(sendmsg("hippa1"), loop=loop),
asyncio.ensure_future(sendmsg("hippa2"), loop=loop),
asyncio.ensure_future(sendmsg("hippa3"), loop=loop)
]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
在示例中,我想用不同的字符串启动三个工作线程并等待它们完成。工人睡眠的时间是随机的,所以我希望他们在脚本多次运行时以随机顺序完成。事实证明,它们似乎是按顺序执行的,第二个线程在第一个线程之后开始。
我的错误是什么? sleep 不应该只阻塞它所在的线程吗?我的事件循环设置正确吗?我可以异步/等待加入吗?
最终我想向其他线程发送消息并等待它们的响应,然后运行带有返回值的回调函数。
编辑:为了澄清,最终我想在我的主线程中等待带有 async/await 的条件变量并运行其他代码,直到一些条件变量让执行通过。在这个示例代码中,我试图对工作线程的连接做同样的事情。
【问题讨论】:
-
time.sleep不是异步的,试试await asyncio.sleep -
但是它是在一个单独的线程中触发的,所以它不应该只是阻塞单独的线程而不是事件循环所在的主线程吗?我的理解是睡眠是线程,而不是进程阻塞。那么,即使使用 async/await 结构,为什么 join 也会阻塞我的主线程呢?
标签: python asynchronous async-await python-multithreading