Bird
0
0

You want to safely acquire and release a lock using automatic resource cleanup. Which code snippet correctly uses with for this purpose?

hard📝 Application Q15 of 15
Python - Context Managers
You want to safely acquire and release a lock using automatic resource cleanup. Which code snippet correctly uses with for this purpose?
import threading
lock = threading.Lock()

# Choose the correct usage
A) with lock.acquire():
       print('Lock acquired')
B) with lock.acquire:
       print('Lock acquired')
C) with lock:
       print('Lock acquired')
D) with lock.lock():
       print('Lock acquired')
Awith lock.acquire():
Bwith lock.acquire:
Cwith lock.lock():
Dwith lock:
Step-by-Step Solution
Solution:
  1. Step 1: Understand lock context management

    Python's threading.Lock supports the context manager protocol, so you can use with lock: to acquire and release automatically.
  2. Step 2: Analyze options

    with lock: uses with lock:, which is correct. Other options misuse the acquire method or call non-existent methods.
  3. Final Answer:

    with lock: -> Option D
  4. Quick Check:

    Use lock directly in with = with lock: [OK]
Quick Trick: Use 'with lock:' to auto acquire and release locks [OK]
Common Mistakes:
  • Calling lock.acquire() inside with
  • Using wrong method names
  • Not knowing Lock supports context manager

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes