Debian Codegraph @

test/units/_internal/test_locking.py

raw
1 from __future__ import annotations
2
3 import time
4 import threading
5 import os
6
7 from concurrent.futures import ThreadPoolExecutor, wait
8
9 from ansible._internal import _locking
10
11
12 def test_blocking_lock(tmp_path: str) -> None:
13 """Validate synchronization behavior of `named_mutex`."""
14 work_count = 0
15 running_threads: set[int] = set()
16
17 def exercise_lock() -> None:
18 nonlocal work_count
19
20 with _locking.named_mutex(os.path.join(tmp_path, "ansible-core")):
21 thread_id = threading.current_thread().native_id
22
23 try:
24 assert not running_threads
25
26 running_threads.add(thread_id)
27 work_count += 1
28 time.sleep(0.1)
29 finally:
30 running_threads.remove(thread_id)
31
32 with ThreadPoolExecutor(max_workers=10) as executor:
33 jobs = [executor.submit(exercise_lock) for _idx in range(10)]
34
35 wait(jobs, 5)
36
37 assert all(job.result() is None for job in jobs)
38 assert work_count == 10