@@ -2854,5 +2854,60 @@ def testfunc(n, m):
28542854 self .assertIn ("_FOR_ITER_TIER_TWO" , uops )
28552855
28562856
2857+ @unittest .skipUnless (support .Py_GIL_DISABLED , 'need Py_GIL_DISABLED' )
2858+ class TestPyThreadId (unittest .TestCase ):
2859+ def test_py_thread_id (self ):
2860+ # gh-112535: Test _Py_ThreadId(): make sure that thread identifiers
2861+ # in a few threads are unique
2862+ py_thread_id = _testinternalcapi .py_thread_id
2863+ short_sleep = 0.010
2864+
2865+ class GetThreadId (threading .Thread ):
2866+ def __init__ (self ):
2867+ super ().__init__ ()
2868+ self .get_lock = threading .Lock ()
2869+ self .get_lock .acquire ()
2870+ self .started_lock = threading .Event ()
2871+ self .py_tid = None
2872+
2873+ def run (self ):
2874+ self .started_lock .set ()
2875+ self .get_lock .acquire ()
2876+ self .py_tid = py_thread_id ()
2877+ time .sleep (short_sleep )
2878+ self .py_tid2 = py_thread_id ()
2879+
2880+ nthread = 5
2881+ threads = [GetThreadId () for _ in range (nthread )]
2882+
2883+ # first make run sure that all threads are running
2884+ for thread in threads :
2885+ thread .start ()
2886+ for thread in threads :
2887+ thread .started_lock .wait ()
2888+
2889+ # call _Py_ThreadId() in the main thread
2890+ py_thread_ids = [py_thread_id ()]
2891+
2892+ # now call _Py_ThreadId() in each thread
2893+ for thread in threads :
2894+ thread .get_lock .release ()
2895+
2896+ # call _Py_ThreadId() in each thread and wait until threads complete
2897+ for thread in threads :
2898+ thread .join ()
2899+ py_thread_ids .append (thread .py_tid )
2900+ # _PyThread_Id() should not change for a given thread.
2901+ # For example, it should remain the same after a short sleep.
2902+ self .assertEqual (thread .py_tid2 , thread .py_tid )
2903+
2904+ # make sure that all _Py_ThreadId() are unique
2905+ for tid in py_thread_ids :
2906+ self .assertIsInstance (tid , int )
2907+ self .assertGreater (tid , 0 )
2908+ self .assertEqual (len (set (py_thread_ids )), len (py_thread_ids ),
2909+ py_thread_ids )
2910+
2911+
28572912if __name__ == "__main__" :
28582913 unittest .main ()
0 commit comments