diff options
author | Victor Stinner <vstinner@python.org> | 2023-12-04 22:40:06 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-12-04 22:40:06 (GMT) |
commit | c5fa8a54dbdf564d482e2e3857aa3efa61edd329 (patch) | |
tree | 9ccea9297f4d21823ea5ed7fb045f1d97b3ce988 /Lib/test/test_capi/test_misc.py | |
parent | a8ce149628c9eaafb8c38fbf25fbd1ed483d2902 (diff) | |
download | cpython-c5fa8a54dbdf564d482e2e3857aa3efa61edd329.zip cpython-c5fa8a54dbdf564d482e2e3857aa3efa61edd329.tar.gz cpython-c5fa8a54dbdf564d482e2e3857aa3efa61edd329.tar.bz2 |
gh-112535: Add test on _Py_ThreadId() (#112709)
Add also test.support.Py_GIL_DISABLED constant.
Diffstat (limited to 'Lib/test/test_capi/test_misc.py')
-rw-r--r-- | Lib/test/test_capi/test_misc.py | 55 |
1 files changed, 55 insertions, 0 deletions
diff --git a/Lib/test/test_capi/test_misc.py b/Lib/test/test_capi/test_misc.py index 6cbf5d2..3d86ae3 100644 --- a/Lib/test/test_capi/test_misc.py +++ b/Lib/test/test_capi/test_misc.py @@ -2854,5 +2854,60 @@ class TestUops(unittest.TestCase): self.assertIn("_FOR_ITER_TIER_TWO", uops) +@unittest.skipUnless(support.Py_GIL_DISABLED, 'need Py_GIL_DISABLED') +class TestPyThreadId(unittest.TestCase): + def test_py_thread_id(self): + # gh-112535: Test _Py_ThreadId(): make sure that thread identifiers + # in a few threads are unique + py_thread_id = _testinternalcapi.py_thread_id + short_sleep = 0.010 + + class GetThreadId(threading.Thread): + def __init__(self): + super().__init__() + self.get_lock = threading.Lock() + self.get_lock.acquire() + self.started_lock = threading.Event() + self.py_tid = None + + def run(self): + self.started_lock.set() + self.get_lock.acquire() + self.py_tid = py_thread_id() + time.sleep(short_sleep) + self.py_tid2 = py_thread_id() + + nthread = 5 + threads = [GetThreadId() for _ in range(nthread)] + + # first make run sure that all threads are running + for thread in threads: + thread.start() + for thread in threads: + thread.started_lock.wait() + + # call _Py_ThreadId() in the main thread + py_thread_ids = [py_thread_id()] + + # now call _Py_ThreadId() in each thread + for thread in threads: + thread.get_lock.release() + + # call _Py_ThreadId() in each thread and wait until threads complete + for thread in threads: + thread.join() + py_thread_ids.append(thread.py_tid) + # _PyThread_Id() should not change for a given thread. + # For example, it should remain the same after a short sleep. + self.assertEqual(thread.py_tid2, thread.py_tid) + + # make sure that all _Py_ThreadId() are unique + for tid in py_thread_ids: + self.assertIsInstance(tid, int) + self.assertGreater(tid, 0) + self.assertEqual(len(set(py_thread_ids)), len(py_thread_ids), + py_thread_ids) + + if __name__ == "__main__": unittest.main() |