// lesson: goroutines-basics
Threads Basics
A threading.Thread is an OS-backed thread managed by the Python runtime.
In CPython (the runtime almost everyone uses), the Global Interpreter Lock
(GIL) lets only one thread execute Python bytecode at a time, so threads
don't run Python bytecode in true parallel โ but the GIL is released during
I/O and by some C-level operations, so threads still overlap I/O and
blocking work. This course uses threads to practice coordinating concurrent
tasks โ the coordination patterns are the point, not raw CPU speedup.
import threading
def worker():
print("hello from a thread")
threading.Thread(target=worker).start()
Thread.start() begins running target in a new thread and returns
immediately โ the calling thread keeps going without waiting. Python's
default (non-daemon) threads do keep the process alive until they finish,
even if you never call .join(), but that isn't the same as your own code
knowing when a thread is done. Call .join() on a thread to block until it
completes, which is how you safely use a value a thread produced โ the
sum_nums challenge below needs both halves' sums before it can add them,
so it must join both threads first. (A thread started with daemon=True
is the exception: the process kills it outright on exit, unjoined.)
โบ Run Work Concurrently
10 ptsImplement sum_nums(nums) so that it splits the list in half and sums each
half in its own thread, combining the results.
Log in to submit a solution and earn points.