← Lesson
Async in Simple Words
Joeven
Run
Reset
Python loads on first run
from collections import deque jobs = [ {"name": "search", "wait": 3}, {"name": "read", "wait": 2}, {"name": "embed", "wait": 4}, ] print("one after another", sum(j["wait"] for j in jobs)) print("all at once", max(j["wait"] for j in jobs)) pending = deque({"name": j["name"], "left": j["wait"]} for j in jobs) inflight = [] max_in_flight = 2 t = 0 print("queue run, max in flight", max_in_flight) while pending or inflight: while pending and len(inflight) < max_in_flight: job = pending.popleft() inflight.append(job) print("t", t, "start", job["name"]) t += 1 still = [] for job in inflight: job["left"] -= 1 if job["left"] <= 0: print("t", t, "done", job["name"]) else: still.append(job) inflight = still print("wall ticks", t)
Run to execute this in your browser. Nothing is sent to a server.