1a
Write a function worker(name) that prints name starting, sleeps for a second and prints name done. Start five threads that run it, as worker-0 to worker-4. Do not join them. Run the cell.
Hint 1
The slide Simple Thread shows how to create and start a Thread with target and args. args takes a tuple.
Check your output
worker-0 starting
worker-1 starting
worker-2 starting
worker-3 starting
worker-4 starting
worker-0 done
worker-1 done
worker-2 done
worker-3 done
worker-4 doneThe five starting lines come together, and the done lines follow a second later. The order within each group can differ, and a notebook can show the done lines under the output of the next cell you run.
Show solutionHide solution
def worker(name: str) -> None:
print(f"{name} starting")
time.sleep(1)
print(f"{name} done")
threads = [threading.Thread(target=worker, args=(f"worker-{i}",)) for i in range(5)]
for t in threads:
t.start()