Debian Codegraph @

pyinstrument/low_level/pyi_timing_thread_python.py

raw symbols SCIP
1 import threading
2 import time
3
4 current_time = 0.0
5
6 subscriber_lock = threading.Lock()
7 update_lock = threading.Lock()
8 thread_should_exit = False
9 thread_alive = False
10
11
12 class Subscription:
13 def __init__(self, interval: float, id: int):
14 self.interval = interval
15 self.id = id
16
17
18 subscribers = []
19
20
21 def get_interval(max_interval: float):
22 if subscribers:
23 return min(sub.interval for sub in subscribers)
24 return max_interval
25
26
27 def timing_thread():
28 global current_time, thread_should_exit
29
30 while not thread_should_exit:
31 interval = get_interval(1.0)
32 acquired = update_lock.acquire(timeout=interval)
33 if acquired:
34 update_lock.release()
35 current_time = time.perf_counter()
36
37
38 def pyi_timing_thread_subscribe(desired_interval: float):
39 global thread_alive, thread_should_exit, current_time
40
41 with subscriber_lock:
42 if not thread_alive:
43 update_lock.acquire()
44 thread_should_exit = False
45 threading.Thread(target=timing_thread).start()
46 thread_alive = True
47 current_time = time.perf_counter()
48
49 ids = [sub.id for sub in subscribers]
50 new_id = 0
51 while new_id in ids:
52 new_id += 1
53
54 subscribers.append(Subscription(desired_interval, new_id))
55
56 update_lock.release()
57 update_lock.acquire()
58
59 return new_id
60
61
62 def pyi_timing_thread_unsubscribe(id: int):
63 with subscriber_lock:
64 subscriber_to_remove = next((sub for sub in subscribers if sub.id == id), None)
65
66 if subscriber_to_remove:
67 subscribers.remove(subscriber_to_remove)
68
69 if not subscribers:
70 global thread_should_exit, thread_alive
71 thread_should_exit = True
72 update_lock.release()
73 thread_alive = False
74 return 0
75 else:
76 raise Exception("PYI_TIMING_THREAD_NOT_SUBSCRIBED")
77
78
79 def pyi_timing_thread_get_time() -> float:
80 return current_time
81
82
83 def pyi_timing_thread_get_interval() -> float:
84 return get_interval(float("inf")) if thread_alive else -1.0