I'm making multiple calls to a 3rd party lib using asyncio tasks, wrapped in a function run_task, which is CPU intensive.
I tried using asyncio.to_thread to run it in a separate thread but I am getting errors
Here is a simplified, correct version of my code, using shazamio.
import asyncio
from shazamio import Shazam
async def run_task(shazam):
ret = await asyncio.to_thread(shazam.recognize_song, '01 - Forest Drive West - Impulse.mp3')
print(ret)
return 1
async def run_all_tasks(iters):
shazam = Shazam()
loop = asyncio.get_event_loop()
coros = [run_task(shazam) for i in range(iters)]
await asyncio.gather(*coros)
return
if __name__ == '__main__':
asyncio.run(run_all_tasks(10))
With this I get ret is a coroutine, so the await did not work. I also get these warnings
<coroutine object Shazam.recognize_song at 0x11054bf10>
/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/asyncio/base_events.py:1936: RuntimeWarning: coroutine 'Shazam.recognize_song' was never awaited
handle = self._ready.popleft()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
asyncio.to_threadtakes a function as an argument, not a coroutine. It'sasyncio.to_thread(shazam.recognize_song, 'SomeFile.mp3')shazam.recognize_songby time.sleep, but with asyncio.sleep i get the same weird behaviour and warningshazam.recognize_songdoes return a coroutine that you could justawaitalready? Then you should not useto_threadat all!asyncio.to_threadtakes a synchronous function as its argument, not a coroutine function.