from threading import Thread
def get_data():
result = database.query() return result
def send_mail(): result = mailer.send() return result
t1 = Thread(target=get_data)t2 = Thread(target=send_mail)
t1.start()t2.start()
t1.join()t2.join()
from multiprocessing import Process
def calculate_fibonacci(): result = fibonacci(100) return result
def calculate_pi(): result = digits_of_pi(100) return result
p1 = Process(target=calculate_fibonacci)p2 = Process(target=calculate_pi)
p1.start()p2.start()
p1.join()p2.join()
import aioextensions# ^ Fluid Attacks library with asyncio utils to simplify its usage
async def get_data(): result = await database.query() # ^ This will take a while. Keep going and we'll talk later return result
async def send_mail(): result = await mailer.send() return result
# While get_data waits for its query, send_mail will be executed# It's doing multiple things at the same time 🙌await aioextensions.collect([ get_data(), send_mail(),])
import asyncioimport aioextensions
async def get_data(): print("get_data started") await asyncio.sleep(5) print("get_data finished")
async def send_mail(): print("send_mail started") await asyncio. sleep(3) print("send_mail finished")
aioextensions.run( aioextensions.collect([ get_data(), send_mail(), ]))
import asyncioimport aioextensionsimport time
async def get_data(): print("get_data started") time.sleep(5)
# ^ From the good old standard library, what could go wrong? print("get_data finished")
async def send_mail(): print("send_mail started") await asyncio.sleep(3) print("send_mail finished")
# 😰 Oh no, get_data calls a ⌛️ blocking function# send_mail will not even be triggered until it finishes!aioextensions.run( aioextensions.collect([ get_data(), send_mail(), ]))
in_thread
to make them non-blocking.
asyncio
way of doing things.
in_thread
as good as native asyncio? Why don’t we just use it everywhere?
await
).
requests
urllib.request.urlopen
time.sleep
subprocess.run
open
(including
file.read
,
file.write
, and
file.seeks
).
in_process
to run 🌐 I/O-bound functions?async def
but never use await inside? async def do_something(): return "Hello world"