Debian Codegraph @

Lib/test/test_free_threading/test_monitoring.py

raw
1 """Tests monitoring, sys.settrace, and sys.setprofile in a multi-threaded
2 environment to verify things are thread-safe in a free-threaded build"""
3
4 import sys
5 import threading
6 import time
7 import unittest
8 import weakref
9
10 from sys import monitoring
11 from test.support import threading_helper
12 from threading import Thread, _PyRLock, Barrier
13 from unittest import TestCase
14
15
16 class InstrumentationMultiThreadedMixin:
17 thread_count = 10
18 func_count = 50
19 fib = 12
20
21 def after_threads(self):
22 """Runs once after all the threads have started"""
23 pass
24
25 def during_threads(self):
26 """Runs repeatedly while the threads are still running"""
27 pass
28
29 def work(self, n, funcs):
30 """Fibonacci function which also calls a bunch of random functions"""
31 for func in funcs:
32 func()
33 if n < 2:
34 return n
35 return self.work(n - 1, funcs) + self.work(n - 2, funcs)
36
37 def start_work(self, n, funcs, barrier):
38 # With the GIL builds we need to make sure that the hooks have
39 # a chance to run as it's possible to run w/o releasing the GIL.
40 barrier.wait()
41 self.work(n, funcs)
42
43 def after_test(self):
44 """Runs once after the test is done"""
45 pass
46
47 def test_instrumentation(self):
48 # Setup a bunch of functions which will need instrumentation...
49 funcs = []
50 for i in range(self.func_count):
51 x = {}
52 exec("def f(): pass", x)
53 funcs.append(x["f"])
54
55 barrier = Barrier(self.thread_count + 1)
56 threads = []
57 for i in range(self.thread_count):
58 # Each thread gets a copy of the func list to avoid contention
59 t = Thread(target=self.start_work, args=(self.fib, list(funcs), barrier))
60 t.start()
61 threads.append(t)
62
63 self.after_threads()
64 barrier.wait()
65
66 while True:
67 any_alive = False
68 for t in threads:
69 if t.is_alive():
70 any_alive = True
71 break
72
73 if not any_alive:
74 break
75
76 self.during_threads()
77 # Sleep to avoid setting monitoring events too rapidly and
78 # overflowing the global version counter
79 time.sleep(0.0001)
80
81 self.after_test()
82
83
84 class MonitoringTestMixin:
85 def setUp(self):
86 for i in range(6):
87 if monitoring.get_tool(i) is None:
88 self.tool_id = i
89 monitoring.use_tool_id(i, self.__class__.__name__)
90 break
91
92 def tearDown(self):
93 monitoring.free_tool_id(self.tool_id)
94
95
96 @threading_helper.requires_working_threading()
97 class SetPreTraceMultiThreaded(InstrumentationMultiThreadedMixin, TestCase):
98 """Sets tracing one time after the threads have started"""
99
100 def setUp(self):
101 super().setUp()
102 self.called = False
103
104 def after_test(self):
105 self.assertTrue(self.called)
106
107 def trace_func(self, frame, event, arg):
108 self.called = True
109 return self.trace_func
110
111 def after_threads(self):
112 sys.settrace(self.trace_func)
113
114
115 @threading_helper.requires_working_threading()
116 class MonitoringMultiThreaded(
117 MonitoringTestMixin, InstrumentationMultiThreadedMixin, TestCase
118 ):
119 """Uses sys.monitoring and repeatedly toggles instrumentation on and off"""
120
121 def setUp(self):
122 super().setUp()
123 self.set = False
124 monitoring.register_callback(
125 self.tool_id, monitoring.events.LINE, self.callback
126 )
127
128 def tearDown(self):
129 monitoring.set_events(self.tool_id, 0)
130 super().tearDown()
131
132 def callback(self, *args):
133 pass
134
135 def during_threads(self):
136 if self.set:
137 monitoring.set_events(
138 self.tool_id, monitoring.events.CALL | monitoring.events.LINE
139 )
140 else:
141 monitoring.set_events(self.tool_id, 0)
142 self.set = not self.set
143
144
145 @threading_helper.requires_working_threading()
146 class SetTraceMultiThreaded(InstrumentationMultiThreadedMixin, TestCase):
147 """Uses sys.settrace and repeatedly toggles instrumentation on and off"""
148
149 def setUp(self):
150 self.set = False
151
152 def tearDown(self):
153 sys.settrace(None)
154
155 def trace_func(self, frame, event, arg):
156 return self.trace_func
157
158 def during_threads(self):
159 if self.set:
160 sys.settrace(self.trace_func)
161 else:
162 sys.settrace(None)
163 self.set = not self.set
164
165
166 @threading_helper.requires_working_threading()
167 class SetProfileMultiThreaded(InstrumentationMultiThreadedMixin, TestCase):
168 """Uses sys.setprofile and repeatedly toggles instrumentation on and off"""
169
170 def setUp(self):
171 self.set = False
172
173 def tearDown(self):
174 sys.setprofile(None)
175
176 def trace_func(self, frame, event, arg):
177 return self.trace_func
178
179 def during_threads(self):
180 if self.set:
181 sys.setprofile(self.trace_func)
182 else:
183 sys.setprofile(None)
184 self.set = not self.set
185
186
187 @threading_helper.requires_working_threading()
188 class SetProfileAllThreadsMultiThreaded(InstrumentationMultiThreadedMixin, TestCase):
189 """Uses threading.setprofile_all_threads and repeatedly toggles instrumentation on and off"""
190
191 def setUp(self):
192 self.set = False
193
194 def tearDown(self):
195 threading.setprofile_all_threads(None)
196
197 def trace_func(self, frame, event, arg):
198 return self.trace_func
199
200 def during_threads(self):
201 if self.set:
202 threading.setprofile_all_threads(self.trace_func)
203 else:
204 threading.setprofile_all_threads(None)
205 self.set = not self.set
206
207
208 @threading_helper.requires_working_threading()
209 class SetProfileAllMultiThreaded(TestCase):
210 def test_profile_all_threads(self):
211 done = threading.Event()
212
213 def func():
214 pass
215
216 def bg_thread():
217 while not done.is_set():
218 func()
219 func()
220 func()
221 func()
222 func()
223
224 def my_profile(frame, event, arg):
225 return None
226
227 bg_threads = []
228 for i in range(10):
229 t = threading.Thread(target=bg_thread)
230 t.start()
231 bg_threads.append(t)
232
233 for i in range(100):
234 threading.setprofile_all_threads(my_profile)
235 threading.setprofile_all_threads(None)
236
237 done.set()
238 for t in bg_threads:
239 t.join()
240
241
242 @threading_helper.requires_working_threading()
243 class MonitoringMisc(MonitoringTestMixin, TestCase):
244 def register_callback(self):
245 def callback(*args):
246 pass
247
248 for i in range(200):
249 monitoring.register_callback(self.tool_id, monitoring.events.LINE, callback)
250
251 self.refs.append(weakref.ref(callback))
252
253 def test_register_callback(self):
254 self.refs = []
255 threads = []
256 for i in range(50):
257 t = Thread(target=self.register_callback)
258 t.start()
259 threads.append(t)
260
261 for thread in threads:
262 thread.join()
263
264 monitoring.register_callback(self.tool_id, monitoring.events.LINE, None)
265 for ref in self.refs:
266 self.assertEqual(ref(), None)
267
268 def test_set_local_trace_opcodes(self):
269 def trace(frame, event, arg):
270 frame.f_trace_opcodes = True
271 return trace
272
273 loops = 1_000
274
275 sys.settrace(trace)
276 try:
277 l = _PyRLock()
278
279 def f():
280 for i in range(loops):
281 with l:
282 pass
283
284 t = Thread(target=f)
285 t.start()
286 for i in range(loops):
287 with l:
288 pass
289 t.join()
290 finally:
291 sys.settrace(None)
292
293
294 if __name__ == "__main__":
295 unittest.main()