4/28
Part 1 of 6 · Why threadsLearn and do
Start every thread before you join any
A thread runs one function. Give threading.Thread the function as target and its arguments as args, start it, and wait for it to end with join:
import threading
import time
def nap(name, out):
time.sleep(0.1)
out.append(name)
out = []
t = threading.Thread(target=nap, args=("a", out))
t.start()
t.join()
print(out)
['a']
A join waits for its thread to finish, so joining each one right after starting it runs them one at a time again. Start them all first.
In the editor, fake_fetch(url, out) stands in for a fetch: it sleeps 0.1 s, like a wait on the network, and records the page in out. Set threads to one threading.Thread per URL, then start them all before you join any, so the eight waits overlap.