I am writing an asynchronous python program that does many async functions, but unfortunately has to read a serial port, and serial
is not async compatible, so I need to utilize a synchronous function to read the serial port, but don't want to block the async functions.
I have managed to complete this by doing:
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())
But my concern here is that I may be spawning multiple threads that will pile up eventually and cause problems. If this is a valid concern, is there a way to see the active threads?