CodeBlanks Logo Icon CodeBlanks

Lock

Learn critical sections with threading.Lock.

What is threading.Lock?

threading.Lock ensures only one thread at a time accesses a shared resource. .acquire() takes the lock and .release() frees it.

A critical section is a code region where multiple threads write to the same resource. Without a lock two threads may write simultaneously and cause a race condition. With Lock you protect this region: the first thread acquires, and others wait until it releases. This is the fundamental safety tool of threaded programming.

Using with Lock

The with lock: block automatically takes and frees the lock. It is safer than writing acquire/release; even if an exception occurs the lock is freed automatically.

This pattern is known as a context manager. Entering the block calls acquire; leaving calls release. Forgetting to unlock is a common mistake; with prevents it. Production code should always prefer with lock:.

Practice Critical section with Lock

Import with from threading import Lock. Create a lock with lock = Lock(). Call lock.acquire(), do print("kritik"), call lock.release().

Starter code

main.py
# create a lock
# protect the critical section
# print

Sample solution

main.py
from threading import Lock

lock = Lock()
lock.acquire()
print("critical")
lock.release()

Expected output

kritik

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does Lock.acquire do?

main.py
lock = Lock()
lock.acquire()
# critical section
lock.release()
  • Returns the lock state
  • Deletes the lock
  • Releases the lock
  • Takes the lock, waits if held Correct answer

Explanation: acquire takes the lock; if another thread holds it, it waits.

2 Complete the acquire call

Question
lock = Lock()
lock.____()
print("kritik")
lock.release()
Answer
lock = Lock()
lock.acquire()
print("kritik")
lock.release()

Explanation: acquire() takes the lock.

3 Match Lock concepts

Term Meaning
Lock Lock object
acquire Takes the lock
release Frees the lock
critical section Protected code

All lessons in Expert