@@ -2854,5 +2854,53 @@ def testfunc(n, m):
2854
2854
self .assertIn ("_FOR_ITER_TIER_TWO" , uops )
2855
2855
2856
2856
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
+
2864
+ class GetThreadId (threading .Thread ):
2865
+ def __init__ (self ):
2866
+ super ().__init__ ()
2867
+ self .get_lock = threading .Lock ()
2868
+ self .get_lock .acquire ()
2869
+ self .started_lock = threading .Event ()
2870
+ self .py_tid = None
2871
+
2872
+ def run (self ):
2873
+ self .started_lock .set ()
2874
+ self .get_lock .acquire ()
2875
+ self .py_tid = py_thread_id ()
2876
+
2877
+ nthread = 5
2878
+ threads = [GetThreadId () for _ in range (nthread )]
2879
+
2880
+ # first make run sure that all threads are running
2881
+ for thread in threads :
2882
+ thread .start ()
2883
+ for thread in threads :
2884
+ thread .started_lock .wait ()
2885
+
2886
+ # call _Py_ThreadId() in the main thread
2887
+ py_thread_ids = [py_thread_id ()]
2888
+
2889
+ # now call _Py_ThreadId() in each thread
2890
+ for thread in threads :
2891
+ thread .get_lock .release ()
2892
+
2893
+ # call _Py_ThreadId() in each thread and wait until threads complete
2894
+ for thread in threads :
2895
+ thread .join ()
2896
+ py_thread_ids .append (thread .py_tid )
2897
+ for tid in py_thread_ids :
2898
+ self .assertIsInstance (tid , int )
2899
+
2900
+ # make sure that all _Py_ThreadId() are unique
2901
+ self .assertEqual (len (set (py_thread_ids )), len (py_thread_ids ),
2902
+ py_thread_ids )
2903
+
2904
+
2857
2905
if __name__ == "__main__" :
2858
2906
unittest .main ()
0 commit comments