Debian Codegraph @

Modules/_testinternalcapi/test_lock.c

raw
1 // C Extension module to test pycore_lock.h API
2
3 #include "parts.h"
4 #include "pycore_lock.h"
5 #include "pycore_pythread.h" // PyThread_get_thread_ident_ex()
6
7 #include "clinic/test_lock.c.h"
8
9 #ifdef MS_WINDOWS
10 #define WIN32_LEAN_AND_MEAN
11 #include <windows.h>
12 #else
13 #include <unistd.h> // usleep()
14 #endif
15
16 /*[clinic input]
17 module _testinternalcapi
18 [clinic start generated code]*/
19 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=7bb583d8c9eb9a78]*/
20
21
22 static void
23 pysleep(int ms)
24 {
25 #ifdef MS_WINDOWS
26 Sleep(ms);
27 #else
28 usleep(ms * 1000);
29 #endif
30 }
31
32 static PyObject *
33 test_lock_basic(PyObject *self, PyObject *obj)
34 {
35 PyMutex m = (PyMutex){0};
36
37 // uncontended lock and unlock
38 PyMutex_Lock(&m);
39 assert(m._bits == 1);
40 PyMutex_Unlock(&m);
41 assert(m._bits == 0);
42
43 Py_RETURN_NONE;
44 }
45
46 struct test_lock2_data {
47 PyMutex m;
48 PyEvent done;
49 int started;
50 };
51
52 static void
53 lock_thread(void *arg)
54 {
55 struct test_lock2_data *test_data = arg;
56 PyMutex *m = &test_data->m;
57 _Py_atomic_store_int(&test_data->started, 1);
58
59 PyMutex_Lock(m);
60 // gh-135641: in rare cases the lock may still have `_Py_HAS_PARKED` set
61 // (m->_bits == 3) due to bucket collisions in the parking lot hash table
62 // between this mutex and the `test_data.done` event.
63 assert(m->_bits == 1 || m->_bits == 3);
64
65 PyMutex_Unlock(m);
66 assert(m->_bits == 0);
67
68 _PyEvent_Notify(&test_data->done);
69 }
70
71 static PyObject *
72 test_lock_two_threads(PyObject *self, PyObject *obj)
73 {
74 // lock attempt by two threads
75 struct test_lock2_data test_data;
76 memset(&test_data, 0, sizeof(test_data));
77
78 PyMutex_Lock(&test_data.m);
79 assert(test_data.m._bits == 1);
80
81 PyThread_start_new_thread(lock_thread, &test_data);
82
83 // wait up to two seconds for the lock_thread to attempt to lock "m"
84 int iters = 0;
85 uint8_t v;
86 do {
87 pysleep(10); // allow some time for the other thread to try to lock
88 v = _Py_atomic_load_uint8_relaxed(&test_data.m._bits);
89 assert(v == 1 || v == 3);
90 iters++;
91 } while (v != 3 && iters < 200);
92
93 // both the "locked" and the "has parked" bits should be set
94 assert(test_data.m._bits == 3);
95
96 PyMutex_Unlock(&test_data.m);
97 PyEvent_Wait(&test_data.done);
98 assert(test_data.m._bits == 0);
99
100 Py_RETURN_NONE;
101 }
102
103 #define COUNTER_THREADS 5
104 #define COUNTER_ITERS 10000
105
106 struct test_data_counter {
107 PyMutex m;
108 Py_ssize_t counter;
109 };
110
111 struct thread_data_counter {
112 struct test_data_counter *test_data;
113 PyEvent done_event;
114 };
115
116 static void
117 counter_thread(void *arg)
118 {
119 struct thread_data_counter *thread_data = arg;
120 struct test_data_counter *test_data = thread_data->test_data;
121
122 for (Py_ssize_t i = 0; i < COUNTER_ITERS; i++) {
123 PyMutex_Lock(&test_data->m);
124 test_data->counter++;
125 PyMutex_Unlock(&test_data->m);
126 }
127 _PyEvent_Notify(&thread_data->done_event);
128 }
129
130 static PyObject *
131 test_lock_counter(PyObject *self, PyObject *obj)
132 {
133 // Test with rapidly locking and unlocking mutex
134 struct test_data_counter test_data;
135 memset(&test_data, 0, sizeof(test_data));
136
137 struct thread_data_counter thread_data[COUNTER_THREADS];
138 memset(&thread_data, 0, sizeof(thread_data));
139
140 for (Py_ssize_t i = 0; i < COUNTER_THREADS; i++) {
141 thread_data[i].test_data = &test_data;
142 PyThread_start_new_thread(counter_thread, &thread_data[i]);
143 }
144
145 for (Py_ssize_t i = 0; i < COUNTER_THREADS; i++) {
146 PyEvent_Wait(&thread_data[i].done_event);
147 }
148
149 assert(test_data.counter == COUNTER_THREADS * COUNTER_ITERS);
150 Py_RETURN_NONE;
151 }
152
153 #define SLOW_COUNTER_ITERS 100
154
155 static void
156 slow_counter_thread(void *arg)
157 {
158 struct thread_data_counter *thread_data = arg;
159 struct test_data_counter *test_data = thread_data->test_data;
160
161 for (Py_ssize_t i = 0; i < SLOW_COUNTER_ITERS; i++) {
162 PyMutex_Lock(&test_data->m);
163 if (i % 7 == 0) {
164 pysleep(2);
165 }
166 test_data->counter++;
167 PyMutex_Unlock(&test_data->m);
168 }
169 _PyEvent_Notify(&thread_data->done_event);
170 }
171
172 static PyObject *
173 test_lock_counter_slow(PyObject *self, PyObject *obj)
174 {
175 // Test lock/unlock with occasional "long" critical section, which will
176 // trigger handoff of the lock.
177 struct test_data_counter test_data;
178 memset(&test_data, 0, sizeof(test_data));
179
180 struct thread_data_counter thread_data[COUNTER_THREADS];
181 memset(&thread_data, 0, sizeof(thread_data));
182
183 for (Py_ssize_t i = 0; i < COUNTER_THREADS; i++) {
184 thread_data[i].test_data = &test_data;
185 PyThread_start_new_thread(slow_counter_thread, &thread_data[i]);
186 }
187
188 for (Py_ssize_t i = 0; i < COUNTER_THREADS; i++) {
189 PyEvent_Wait(&thread_data[i].done_event);
190 }
191
192 assert(test_data.counter == COUNTER_THREADS * SLOW_COUNTER_ITERS);
193 Py_RETURN_NONE;
194 }
195
196 struct bench_data_locks {
197 int stop;
198 int use_pymutex;
199 int critical_section_length;
200 char padding[200];
201 PyThread_type_lock lock;
202 PyMutex m;
203 double value;
204 Py_ssize_t total_iters;
205 };
206
207 struct bench_thread_data {
208 struct bench_data_locks *bench_data;
209 Py_ssize_t iters;
210 PyEvent done;
211 };
212
213 static void
214 thread_benchmark_locks(void *arg)
215 {
216 struct bench_thread_data *thread_data = arg;
217 struct bench_data_locks *bench_data = thread_data->bench_data;
218 int use_pymutex = bench_data->use_pymutex;
219 int critical_section_length = bench_data->critical_section_length;
220
221 double my_value = 1.0;
222 Py_ssize_t iters = 0;
223 while (!_Py_atomic_load_int_relaxed(&bench_data->stop)) {
224 if (use_pymutex) {
225 PyMutex_Lock(&bench_data->m);
226 for (int i = 0; i < critical_section_length; i++) {
227 bench_data->value += my_value;
228 my_value = bench_data->value;
229 }
230 PyMutex_Unlock(&bench_data->m);
231 }
232 else {
233 PyThread_acquire_lock(bench_data->lock, 1);
234 for (int i = 0; i < critical_section_length; i++) {
235 bench_data->value += my_value;
236 my_value = bench_data->value;
237 }
238 PyThread_release_lock(bench_data->lock);
239 }
240 iters++;
241 }
242
243 thread_data->iters = iters;
244 _Py_atomic_add_ssize(&bench_data->total_iters, iters);
245 _PyEvent_Notify(&thread_data->done);
246 }
247
248 /*[clinic input]
249 _testinternalcapi.benchmark_locks
250
251 num_threads: Py_ssize_t
252 use_pymutex: bool = True
253 critical_section_length: int = 1
254 time_ms: int = 1000
255 /
256
257 [clinic start generated code]*/
258
259 static PyObject *
260 _testinternalcapi_benchmark_locks_impl(PyObject *module,
261 Py_ssize_t num_threads,
262 int use_pymutex,
263 int critical_section_length,
264 int time_ms)
265 /*[clinic end generated code: output=381df8d7e9a74f18 input=f3aeaf688738c121]*/
266 {
267 // Run from Tools/lockbench/lockbench.py
268 // Based on the WebKit lock benchmarks:
269 // https://github.com/WebKit/WebKit/blob/main/Source/WTF/benchmarks/LockSpeedTest.cpp
270 // See also https://webkit.org/blog/6161/locking-in-webkit/
271 PyObject *thread_iters = NULL;
272 PyObject *res = NULL;
273
274 struct bench_data_locks bench_data;
275 memset(&bench_data, 0, sizeof(bench_data));
276 bench_data.use_pymutex = use_pymutex;
277 bench_data.critical_section_length = critical_section_length;
278
279 bench_data.lock = PyThread_allocate_lock();
280 if (bench_data.lock == NULL) {
281 return PyErr_NoMemory();
282 }
283
284 struct bench_thread_data *thread_data = NULL;
285 thread_data = PyMem_Calloc(num_threads, sizeof(*thread_data));
286 if (thread_data == NULL) {
287 PyErr_NoMemory();
288 goto exit;
289 }
290
291 thread_iters = PyList_New(num_threads);
292 if (thread_iters == NULL) {
293 goto exit;
294 }
295
296 PyTime_t start, end;
297 if (PyTime_PerfCounter(&start) < 0) {
298 goto exit;
299 }
300
301 for (Py_ssize_t i = 0; i < num_threads; i++) {
302 thread_data[i].bench_data = &bench_data;
303 PyThread_start_new_thread(thread_benchmark_locks, &thread_data[i]);
304 }
305
306 // Let the threads run for `time_ms` milliseconds
307 pysleep(time_ms);
308 _Py_atomic_store_int(&bench_data.stop, 1);
309
310 // Wait for the threads to finish
311 for (Py_ssize_t i = 0; i < num_threads; i++) {
312 PyEvent_Wait(&thread_data[i].done);
313 }
314
315 Py_ssize_t total_iters = bench_data.total_iters;
316 if (PyTime_PerfCounter(&end) < 0) {
317 goto exit;
318 }
319
320 // Return the total number of acquisitions and the number of acquisitions
321 // for each thread.
322 for (Py_ssize_t i = 0; i < num_threads; i++) {
323 PyObject *iter = PyLong_FromSsize_t(thread_data[i].iters);
324 if (iter == NULL) {
325 goto exit;
326 }
327 PyList_SET_ITEM(thread_iters, i, iter);
328 }
329
330 assert(end != start);
331 double rate = total_iters * 1e9 / (end - start);
332 res = Py_BuildValue("(dO)", rate, thread_iters);
333
334 exit:
335 PyThread_free_lock(bench_data.lock);
336 PyMem_Free(thread_data);
337 Py_XDECREF(thread_iters);
338 return res;
339 }
340
341 static PyObject *
342 test_lock_benchmark(PyObject *module, PyObject *obj)
343 {
344 // Just make sure the benchmark runs without crashing
345 PyObject *res = _testinternalcapi_benchmark_locks_impl(
346 module, 1, 1, 1, 100);
347 if (res == NULL) {
348 return NULL;
349 }
350 Py_DECREF(res);
351 Py_RETURN_NONE;
352 }
353
354 static int
355 init_maybe_fail(void *arg)
356 {
357 int *counter = (int *)arg;
358 (*counter)++;
359 if (*counter < 5) {
360 // failure
361 return -1;
362 }
363 assert(*counter == 5);
364 return 0;
365 }
366
367 static PyObject *
368 test_lock_once(PyObject *self, PyObject *obj)
369 {
370 _PyOnceFlag once = {0};
371 int counter = 0;
372 for (int i = 0; i < 10; i++) {
373 int res = _PyOnceFlag_CallOnce(&once, init_maybe_fail, &counter);
374 if (i < 4) {
375 assert(res == -1);
376 }
377 else {
378 assert(res == 0);
379 assert(counter == 5);
380 }
381 }
382 Py_RETURN_NONE;
383 }
384
385 struct test_rwlock_data {
386 Py_ssize_t nthreads;
387 _PyRWMutex rw;
388 PyEvent step1;
389 PyEvent step2;
390 PyEvent step3;
391 PyEvent done;
392 };
393
394 static void
395 rdlock_thread(void *arg)
396 {
397 struct test_rwlock_data *test_data = arg;
398
399 // Acquire the lock in read mode
400 _PyRWMutex_RLock(&test_data->rw);
401 PyEvent_Wait(&test_data->step1);
402 _PyRWMutex_RUnlock(&test_data->rw);
403
404 _PyRWMutex_RLock(&test_data->rw);
405 PyEvent_Wait(&test_data->step3);
406 _PyRWMutex_RUnlock(&test_data->rw);
407
408 if (_Py_atomic_add_ssize(&test_data->nthreads, -1) == 1) {
409 _PyEvent_Notify(&test_data->done);
410 }
411 }
412 static void
413 wrlock_thread(void *arg)
414 {
415 struct test_rwlock_data *test_data = arg;
416
417 // First acquire the lock in write mode
418 _PyRWMutex_Lock(&test_data->rw);
419 PyEvent_Wait(&test_data->step2);
420 _PyRWMutex_Unlock(&test_data->rw);
421
422 if (_Py_atomic_add_ssize(&test_data->nthreads, -1) == 1) {
423 _PyEvent_Notify(&test_data->done);
424 }
425 }
426
427 static void
428 wait_until(uintptr_t *ptr, uintptr_t value)
429 {
430 // wait up to two seconds for *ptr == value
431 int iters = 0;
432 uintptr_t bits;
433 do {
434 pysleep(10);
435 bits = _Py_atomic_load_uintptr(ptr);
436 iters++;
437 } while (bits != value && iters < 200);
438 }
439
440 static PyObject *
441 test_lock_rwlock(PyObject *self, PyObject *obj)
442 {
443 struct test_rwlock_data test_data = {.nthreads = 3};
444
445 _PyRWMutex_Lock(&test_data.rw);
446 assert(test_data.rw.bits == 1);
447
448 _PyRWMutex_Unlock(&test_data.rw);
449 assert(test_data.rw.bits == 0);
450
451 // Start two readers
452 PyThread_start_new_thread(rdlock_thread, &test_data);
453 PyThread_start_new_thread(rdlock_thread, &test_data);
454
455 // wait up to two seconds for the threads to attempt to read-lock "rw"
456 wait_until(&test_data.rw.bits, 8);
457 assert(test_data.rw.bits == 8);
458
459 // start writer (while readers hold lock)
460 PyThread_start_new_thread(wrlock_thread, &test_data);
461 wait_until(&test_data.rw.bits, 10);
462 assert(test_data.rw.bits == 10);
463
464 // readers release lock, writer should acquire it
465 _PyEvent_Notify(&test_data.step1);
466 wait_until(&test_data.rw.bits, 3);
467 assert(test_data.rw.bits == 3);
468
469 // writer releases lock, readers acquire it
470 _PyEvent_Notify(&test_data.step2);
471 wait_until(&test_data.rw.bits, 8);
472 assert(test_data.rw.bits == 8);
473
474 // readers release lock again
475 _PyEvent_Notify(&test_data.step3);
476 wait_until(&test_data.rw.bits, 0);
477 assert(test_data.rw.bits == 0);
478
479 PyEvent_Wait(&test_data.done);
480 Py_RETURN_NONE;
481 }
482
483 static PyObject *
484 test_lock_recursive(PyObject *self, PyObject *obj)
485 {
486 _PyRecursiveMutex m = (_PyRecursiveMutex){0};
487 assert(!_PyRecursiveMutex_IsLockedByCurrentThread(&m));
488
489 _PyRecursiveMutex_Lock(&m);
490 assert(m.thread == PyThread_get_thread_ident_ex());
491 assert(PyMutex_IsLocked(&m.mutex));
492 assert(m.level == 0);
493
494 _PyRecursiveMutex_Lock(&m);
495 assert(m.level == 1);
496 _PyRecursiveMutex_Unlock(&m);
497
498 _PyRecursiveMutex_Unlock(&m);
499 assert(m.thread == 0);
500 assert(!PyMutex_IsLocked(&m.mutex));
501 assert(m.level == 0);
502
503 Py_RETURN_NONE;
504 }
505
506 static PyMethodDef test_methods[] = {
507 {"test_lock_basic", test_lock_basic, METH_NOARGS},
508 {"test_lock_two_threads", test_lock_two_threads, METH_NOARGS},
509 {"test_lock_counter", test_lock_counter, METH_NOARGS},
510 {"test_lock_counter_slow", test_lock_counter_slow, METH_NOARGS},
511 _TESTINTERNALCAPI_BENCHMARK_LOCKS_METHODDEF
512 {"test_lock_benchmark", test_lock_benchmark, METH_NOARGS},
513 {"test_lock_once", test_lock_once, METH_NOARGS},
514 {"test_lock_rwlock", test_lock_rwlock, METH_NOARGS},
515 {"test_lock_recursive", test_lock_recursive, METH_NOARGS},
516 {NULL, NULL} /* sentinel */
517 };
518
519 int
520 _PyTestInternalCapi_Init_Lock(PyObject *mod)
521 {
522 if (PyModule_AddFunctions(mod, test_methods) < 0) {
523 return -1;
524 }
525 return 0;
526 }