如何在 python 异步中获取活动线程的数量

How to get quantity of active threads in python async

我正在编写一个异步 python 程序,它执行许多异步功能,但不幸的是必须读取串行端口,并且 serial 不兼容异步,所以我需要利用同步功能读取串行端口,但不想阻止异步功能。

我通过以下方式完成了此任务:

import asyncio
import time

def serialReader():
    while True:
        print("waiting for new serial values")
        time.sleep(4)#simulated waiting on serial port
        return "some serial values"

async def func1():
    while True:
        print("function 1 running")
        await asyncio.sleep(1)

async def serialManager():
    loop = asyncio.get_running_loop()
    while True:
        result = await loop.run_in_executor(None, serialReader)
        print(result)

async def main(): 
    func1Task = asyncio.create_task(func1())
    func2Task = asyncio.create_task(serialManager())
    await func2Task


asyncio.run(main())

但我担心的是我可能会产生多个线程,这些线程最终会堆积起来并导致问题。如果这是一个有效的问题,是否有办法查看活动线程?

您可以使用threading.active_count()获取活动线程数。

来自文档

Return the number of Thread objects currently alive. The returned count is equal to the length of the list returned by enumerate().

当您在 loop.run_in_executor 中使用 None 时,将使用默认执行程序,默认情况下它可以生成的线程数有限制。