Asyncio - create_task 阻塞线程
Asyncio - create_task blocks thread
我正在尝试创建一个 Python 脚本,它将接收来自 websocket 连接的消息,并且每次它接收到一条新消息时,它都需要 运行 在后台执行一个 asyncio 任务。
为了“模拟”这个过程,我制作了一个阻塞函数,它以 while True
语句开始计数。预期的输出是每次从 ws 连接接收到新消息时,都会开始新的计数,但在我的例子中,只要我 运行 脚本,计数函数就会阻塞整个代码。我该如何解决?
这是我尝试过的:
import asyncio
import websockets
import json
import time
#this is the blocking function..
def counter():
count = 0
while True:
print(count)
count += 1
time.sleep(0.5)
async def main():
while True:
try:
async with websockets.connect('MY-URL') as websocket:
while True:
msg = await asyncio.wait_for(websocket.recv(), 500)
try:
data = json.loads(msg)
await loop.create_task(counter())
except Exception as e:
print(e)
except Exception as e:
print(e)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
这里有两个主要问题。您的第一个问题是,您在 counter
中创建了一个无限循环,然后在尝试将其传递给 create_task
时调用它。这样 create_task
甚至都不会被调用。
第二个明显的问题是,您尝试将方法传递给 create_task
而它需要协程。
使用 async def
再次将 counter
方法定义为协程,并将 time.sleep
替换为 asyncio.sleep
,我认为它可能有效。
一般说明:您不能在与事件循环相同的线程中使用阻塞代码。这意味着永远不要在异步代码中使用 time.sleep
...
我正在尝试创建一个 Python 脚本,它将接收来自 websocket 连接的消息,并且每次它接收到一条新消息时,它都需要 运行 在后台执行一个 asyncio 任务。
为了“模拟”这个过程,我制作了一个阻塞函数,它以 while True
语句开始计数。预期的输出是每次从 ws 连接接收到新消息时,都会开始新的计数,但在我的例子中,只要我 运行 脚本,计数函数就会阻塞整个代码。我该如何解决?
这是我尝试过的:
import asyncio
import websockets
import json
import time
#this is the blocking function..
def counter():
count = 0
while True:
print(count)
count += 1
time.sleep(0.5)
async def main():
while True:
try:
async with websockets.connect('MY-URL') as websocket:
while True:
msg = await asyncio.wait_for(websocket.recv(), 500)
try:
data = json.loads(msg)
await loop.create_task(counter())
except Exception as e:
print(e)
except Exception as e:
print(e)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
这里有两个主要问题。您的第一个问题是,您在 counter
中创建了一个无限循环,然后在尝试将其传递给 create_task
时调用它。这样 create_task
甚至都不会被调用。
第二个明显的问题是,您尝试将方法传递给 create_task
而它需要协程。
使用 async def
再次将 counter
方法定义为协程,并将 time.sleep
替换为 asyncio.sleep
,我认为它可能有效。
一般说明:您不能在与事件循环相同的线程中使用阻塞代码。这意味着永远不要在异步代码中使用 time.sleep
...