Suppose there is a library that makes various database queries:
import time
def queryFoo():
time.sleep(4)
return \"foo\"
def queryBar():
time.s
I presume you are after concurrency and hopefully do not insist on using asyncio
module itself in which case this little example could be helpful:
import asyncio
import time
from concurrent.futures import ThreadPoolExecutor
def queryFoo():
time.sleep(2)
return "FOO"
def queryBar():
time.sleep(4)
return "BAR"
with ThreadPoolExecutor(max_workers=2) as executor:
foo = executor.submit(queryFoo)
bar = executor.submit(queryBar)
results = [foo.result(), bar.result()]
print(results)
It runs both queryFoo()
and queryBar()
in parallel and collects their results in a list in order in which they've been mentioned in an assignment to results
.