A thread is a flow of execution inside a process. All the threads of a process share memory (variables, lists…). The threading module creates and manages them.
Creating, starting and waiting for threads
Thread(target=function, args=(...)) creates the thread, start() sets it going and join() blocks the calling thread until the other one finishes.
# Not run in the browser corrector (it cannot create real threads).
import threading
import time
def work(name, pause):
time.sleep(pause)
print(name, "finished")
threads = [threading.Thread(target=work, args=(n, p))
for n, p in (("a", 0.1), ("b", 0.05))]
for h in threads:
h.start() # starts running at the same time
for h in threads:
h.join() # waits until it finishes
print("all finished")
# b finished
# a finished
# all finished
Notice that b finishes before a even though it was launched later: threads advance on their own, and the order depends on how long each one takes. In general you cannot assume an order between threads.
The problem: race conditions
Since threads share data, a danger appears: the race condition. It happens when several threads read and modify the same data and the result depends on the order in which their steps interleave. Even an operation as simple as counter += 1 is not indivisible: it is three steps (read, add 1, write), and the system can switch threads between them.
counter = 0
read_a = counter # thread A reads 0
read_b = counter # thread B reads 0 (before A writes)
counter = read_a + 1 # A writes 1
counter = read_b + 1 # B writes 1: it overwrites the write of A!
print(counter) # 1 (it should be 2)
This bug is hard to debug because it does not always happen: it depends on the exact moment the system switches threads. That is why we simulate it in a deterministic way in Simulated race condition.
The solution: Lock
A Lock lets only one thread at a time into a critical section: the code that touches the shared data. It is usually used with with, which always releases it, even if there is an exception.
# Not run in the browser corrector (it cannot create real threads).
import threading
counter = 0
lock = threading.Lock()
def add(times):
global counter
for _ in range(times):
with lock: # only one thread at a time inside the block
counter += 1
threads = [threading.Thread(target=add, args=(10000,)) for _ in range(4)]
for h in threads:
h.start()
for h in threads:
h.join()
print(counter) # 40000
Without the lock the final result could be less than 40000. With it, it is always exact, but beware: threads wait to get in, so do not overuse locks.
Other synchronization tools
threading.RLock: a lock that the same thread can acquire several times (reentrant).threading.Semaphore(n): lets up tonthreads in at the same time; you simulate it in Semaphore with a waiting queue.threading.Event: a thread tells others that something has happened (set(),wait()).threading.local(): different data for each thread.
Daemon threads
With Thread(..., daemon=True) the thread is a daemon: it does not stop the program from ending when the main thread finishes. Use them for background tasks that can be interrupted.