Lesson 05
Thread Locks
Protect a shared Python task with threading.Lock so one thread finishes the task before the next thread enters, and always release the lock.
Protect a shared Python task with threading.Lock so one thread finishes the task before the next thread enters, and always release the lock.
Example
import threading
lock = threading.Lock()
def show_table(m):
with lock:
print("table", m)
for p in range(1, 4):
print(m, "x", p, "=", m * p)
first = threading.Thread(target=show_table, args=(3,), name="three")
second = threading.Thread(target=show_table, args=(4,), name="four")
first.start()
second.start()
first.join()
second.join()Each table prints as one block: 3 x 1 = 3 through 3 x 3 = 9, then the table for 4. Which table starts first can vary on desktop Python. The lines inside one table do not mix with the other table, because with lock acquires the lock for the block and releases it when the block ends. Without the lock, the two threads can interleave single lines. That mixed output is a race on the shared print. A deadlock is the stricter case: if a thread acquires the lock and never releases it, the next thread waits forever on acquire. with lock releases the lock even when the block raises.
Key takeaways
- A shared section without a lock can interleave two threads' lines
Lock.acquire()lets one thread in and makes the others waitrelease()lets the next thread enter- Forgetting
release()can leave the next thread waiting forever with lockacquires and always releases- Next: Network Overview — a server, a client, and a port on this computer
- Previous: Join and Status
Loading playground…
Check your understanding
Thread Locks Quiz
Which class provides the lock in this lesson?
1 / 10