Sub topic 3
Running tasks in threads
This chapter assumes you can write Python functions and use with statements. It also assumes you know what concurrency and I/O-bound work mean from the earlier chapters. Here you will start threads, wait for them, and handle the errors that trip people up most often.
What a thread is
A thread is a path of execution inside a process. All threads in a process share the same memory, so they can read the same variables and objects. Each thread has its own call stack. Python's threading module wraps operating-system threads, so the OS scheduler decides when each one runs.
Starting and joining a thread
You create a threading.Thread with a target function and its args. Calling start() begins running it. Calling join() blocks the caller until that thread finishes.
import threading
import time
def fetch(name, delay, results):
time.sleep(delay) # stands in for waiting on the network
results[name] = delay
results = {}
threads = [
threading.Thread(target=fetch, args=(f"job{i}", 0.5, results))
for i in range(3)
]
start = time.perf_counter()
for t in threads:
t.start()
for t in threads:
t.join()
print(sorted(results), f"{time.perf_counter() - start:.1f}s")This prints ['job0', 'job1', 'job2'] after about 0.5 seconds, not 1.5. The three waits overlap. Each thread writes to its own dictionary key, so the threads never write to the same place. The next chapter covers what happens when they do.
Common errors
- Calling the function instead of passing it.
target=fetch("a", 1, r)runsfetchimmediately in the current thread and passes its return value,None, as the target. Writetarget=fetch. - Forgetting the tuple comma.
args=(5)is just the integer 5. A single argument needsargs=(5,). - Starting a thread twice. Calling
start()a second time on the same object raisesRuntimeError. Create a newThreadinstead. - Skipping
join(). The main thread may reach the end of your code and read results before the workers have written them.
Return values and exceptions
A thread's target return value is discarded. To get results out, write them into a shared structure, as the example does, or use a pool (covered in the executors chapter).
An exception in a thread does not reach the thread that started it. It ends only that thread, and Python prints the traceback to standard error through threading.excepthook. The main thread keeps running as if nothing happened. If a thread must report failure, catch the exception inside the target and store it with the result.
Daemon threads
By default, Python waits for all non-daemon threads to finish before the program exits. Passing daemon=True marks a thread as a daemon. The interpreter does not wait for daemon threads, and it stops them abruptly at exit. They may be cut off in the middle of a write or while holding a resource. Use them only for background work that is safe to abandon, such as a heartbeat.
Exercise
A learner writes t = threading.Thread(target=work(10)) and notices the program takes the full duration of work(10) before any thread seems to run. What is wrong, and how is it fixed?
Show answer
work(10) is called immediately in the main thread, so the work runs there and the thread receives its return value, usually None, as the target. The fix is threading.Thread(target=work, args=(10,)), which passes the function itself and its arguments separately.