Always Release the Lock

Medium ⏱ 12 min 53% acceptance ★★★★☆ 4.2
You are given a lock object with .acquire() and .release() methods and a task callable that might raise. Write run_locked(lock, task) that acquires, runs the task and returns its result — guaranteeing release() runs even when the task raises (let the exception propagate after releasing). finally is the tool.

Examples

Example 1
Input
run_locked(lock, lambda: 42)
Output
42 (lock released)
Explanation

On success and on failure alike, release() executes.

Constraints

  • Use try/finally.
  • Do not swallow the exception.

Topics

Exception Handlingfinally

Companies

Goldman SachsJPMorgan Chase

Hints

Hint 1

No except clause needed at all.

Hint 2

Code in finally runs on every exit path.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.