gpt4 book ai didi

Python asyncio 等待线程

转载 作者:行者123 更新时间:2023-11-28 19:13:14 25 4
gpt4 key购买 nike

我有一个“服务器”线程,它应该监听来自其他服务器线程的调用/事件,同时执行一些其他代码。最近我经常使用 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()

在示例中,我想启动三个具有不同字符串的工作线程并等待它们完成。 worker 的 sleep 时间是随机的,所以我希望他们在脚本多次运行时以随机顺序完成。事实证明,它们似乎是按顺序执行的,第二个线程在第一个线程之后开始。

我这里的错误是什么? sleep 不应该只阻塞它所在的线程吗?我的事件循环是否设置正确?我可以异步/等待加入吗?

最终我想向其他线程发送消息并等待他们的响应,然后运行一个带有返回值的回调函数。

编辑:澄清一下,最终我想在我的主线程中使用 async/await 等待条件变量并运行其他代码,直到某些条件变量允许执行为止。在这个示例代码中,我试图对工作线程的连接做同样的事情。

最佳答案

最终,由于这段代码,它是顺序运行的:

async def send(message):
t = MyThread(message) # daemon = True
t.start()
print("asd")
return t.join()

您启动一个线程,然后在继续之前立即等待该线程完成。这就是它们按顺序执行的原因。

Node.js 和 asyncio 不一定会创建新线程来执行它们的操作。例如,Node.js 仅使用单个线程,但它使用内核级函数(例如“epoll”)来调用您在某些新网络事件发生时指示的回调。这允许单个线程管理数百个网络连接。

这就是为什么当你在没有 Thread 实例的情况下执行它时,你会在当前运行的线程上调用 sleep ,这与主线程相同。当您将 asyncio 与网络功能一起使用时,您可以使用“yield from”结构,它允许其他代码块在其他任务与其他远程服务进行操作时执行。

主要结构是正确的。你想要这段代码:

loop.run_until_complete(asyncio.wait(tasks))

但是不要依赖'sleep'来测试功能,你需要进行网络调用,或者使用:

yield from asyncio.sleep(1)

而且在这种情况下不需要启动单独的线程。

关于Python asyncio 等待线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37223846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com