+
    BiW                       R t ^ RIt^ RIHtHtHt ^ RIHtHtHt ^ RI	H
t
Ht ^ RIHtHt ^ RIHt ^ RIt^ RIt^ RIt^ RIt^ RIt^ RIt^ RIt^ RIt^ RIt^ RIt^ RIt^ RIt^ RIt^ RIHt ^ RIHt ^ R	IHt  ^ R
I H!t! ]PF                  ! RR7       R>t$R t%R t&R t' ! R R](4      t) ! R R]PT                  4      t+ ! R R]PX                  4      t- ! R R]-4      t. ! R R]-4      t/ ! R R]-4      t0 ! R R]-4      t1 ! R R]PT                  4      t2 ! R  R!]-4      t3 ! R" R#]-4      t4 ! R$ R%]Pj                  4      t5 ! R& R']Pl                  4      t7]Pp                  ! ]Pr                  RJ R(4       ! R) R*]Pl                  4      4       t: ! R+ R,]Pv                  4      t; ! R- R.]Pl                  4      t< ! R/ R0]Pz                  4      t= ! R1 R2]P|                  4      t> ! R3 R4]P~                  4      t? ! R5 R6]P                  4      t@ ! R7 R8]PX                  4      tA ! R9 R:]PX                  4      tB ! R; R<]PX                  4      tC]DR=8X  d   ]P                  ! 4        R# R#   ]" d    Rt! ELi ; i)?z!
Tests for the threading module.
N)threading_helperrequires_subprocessrequires_gil_enabled)verbosecpython_only	os_helper)ensure_lazy_importsimport_module)assert_python_okassert_python_failure)force_not_colorized)mock)
lock_tests)support)interpretersT)modulec                    \         P                  '       g   \        P                  ! R 4      ! V 4      # \        P
                  \        9   d   \        P                  ! R4      ! V 4      # \         P                  '       d   \        P                  ! R4      ! V 4      # \         P                  ! RR7      '       d   \        P                  ! R4      ! V 4      # V # )zrequires working os.fork()z*due to known OS bug related to thread+forkz?libasan has a pthread_create() dead lock related to thread+forkTthreadz'TSAN doesn't support threads after fork)	r   has_fork_supportunittestskipsysplatformplatforms_to_skipHAVE_ASAN_FORK_BUGcheck_sanitizer)tests   &*/usr/lib/python3.14/test/test_threading.pyskip_unless_reliable_forkr   ,   s    ###}}9:4@@
||((}}IJ4PP!!!}}^_`deed++}}FGMMK    c                H    \         P                  ! \        RJ R4      ! V 4      # )z>Decorator to skip a test if subinterpreters are not supported.Nzsubinterpreters required)r   skipIfr   )meths   &r   requires_subinterpretersr$   8   s%    ??<4/577;= =r    c                     V P                  \        \        R \        P                  4       \        P                  \        n        R# )
excepthookN)
addCleanupsetattr	threadingr&   __excepthook__)testcases   &r   restore_default_excepthookr,   >   s*    L):N:NO$33Ir    c                   8   a  ] tR t^Dt o R tR tR tR tRtV t	R# )Counterc                    ^ V n         R#     Nvalueselfs   &r   __init__Counter.__init__E   s	    
r    c                8    V ;P                   ^,          un         R#    Nr2   r4   s   &r   incCounter.incG       

a
r    c                8    V ;P                   ^,          un         R# r9   r2   r4   s   &r   decCounter.decI   r=   r    c                    V P                   # Nr2   r4   s   &r   getCounter.getK   s    zzr    r2   N)
__name__
__module____qualname____firstlineno__r6   r;   r?   rC   __static_attributes____classdictcell____classdict__s   @r   r.   r.   D   s      r    r.   c                   ,   a  ] tR t^Nt o R tR tRtV tR# )
TestThreadc                v    \         P                  P                  WR 7       W n        W0n        W@n        WPn        R# )nameN)r)   Threadr6   r+   semamutexnrunning)r5   rQ   r+   rS   rT   rU   s   &&&&&&r   r6   TestThread.__init__O   s-    !!$!2 	
 r    c           
     R   \         P                   ! 4       R ,          p\        '       d&   \        RV P                  VR,          3,          4       V P                  ;_uu_ 4        V P
                  ;_uu_ 4        V P                  P                  4        \        '       d%   \        V P                  P                  4       R4       V P                  P                  V P                  P                  4       ^4       RRR4       \        P                  ! V4       \        '       d   \        RV P                  R4       V P
                  ;_uu_ 4        V P                  P                  4        V P                  P                  V P                  P                  4       ^ 4       \        '       d7   \        RV P                  V P                  P                  4       3,          4       RRR4       RRR4       R#   + '       g   i     EL; i  + '       g   i     L.; i  + '       g   i     R# ; i)g     @ztask %s will run for %.1f usecg    .Aztasks are runningNtaskdonez$%s is finished. %d tasks are running)randomr   printrQ   rS   rT   rU   r;   rC   r+   assertLessEqualtimesleepr?   assertGreaterEqual)r5   delays   & r   runTestThread.runV   sO   ')7299eck*+ , YYY!!#7$--++-/BC--dmm.?.?.A1E	  JJuwfdii0!!#001B1B1DaH7@99dmm&7&7&9:; <	  Y  YYsD   "H7A?G.	6)H +HBH	H.G?9	HHHH&	)rT   rU   rS   r+   N)rE   rF   rG   rH   r6   ra   rI   rJ   rK   s   @r   rN   rN   N   s     !< <r    rN   c                   ,   a  ] tR t^ot o R tR tRtV tR# )BaseTestCasec                :    \         P                  ! 4       V n        R # rB   )r   threading_setup_threadsr4   s   &r   setUpBaseTestCase.setUpp   s    (88:r    c                ~    \         P                  ! V P                  !   \        P                  P                  4        R # rB   )r   threading_cleanuprg   r   r   reap_childrenr4   s   &r   tearDownBaseTestCase.tearDowns   s$    **DMM:""$r    )rg   N)rE   rF   rG   rH   rh   rm   rI   rJ   rK   s   @r   rd   rd   o   s     ;% %r    rd   c                     a  ] tR t^xt o Rt]R 4       t]R 4       tR tR t	R t
R tR tR	 tR
 tR tR tR tR tR tR tR tR t]P0                  ! ^R;RR7      R 4       tR tR tR tR tR t]R 4       t ]R 4       t!R t"]]#PH                  ! ]%! ]&R4      R4      R  4       4       t']]#PH                  ! ]%! ]&R4      R4      R! 4       4       t(]]#PH                  ! ]%! ]&R4      R4      R<R" l4       4       t)R<R# lt*R$ t+R% t,R& t-R' t.]R( 4       t/R) t0R* t1R+ t2R, t3R- t4R. t5R/ t6R0 t7R1 t8R2 t9R3 t:R4 t;]R5 4       t<]]#PH                  ! ]%! ]=R64      R74      R8 4       4       t>R9t?V t@R:# )=ThreadTestsi'  c                "    \        R RR04       R# )r)   	functoolswarningsN)r   r4   s   &r   test_lazy_importThreadTests.test_lazy_import{   s    K+z)BCr    c                ,   R  p\         P                  ! RR7      pV P                  VP                  R4       \         P                  ! ^{R7      pV P                  VP                  R4       \         P                  ! VRR7      pV P                  VP                  R4       \        P
                  P                  \         R^R7      ;_uu_ 4        \         P                  ! RR7      pV P                  VP                  R	4       R
R
R
4       \        P
                  P                  \         R^R7      ;_uu_ 4        \         P                  ! 4       pV P                  VP                  R4       R
R
R
4       \        P
                  P                  \         R^R7      ;_uu_ 4        \         P                  ! VR7      pV P                  VP                  R4       R
R
R
4       R
#   + '       g   i     L; i  + '       g   i     L; i  + '       g   i     R
# ; i)c                      R # rB    rx   r    r   func#ThreadTests.test_name.<locals>.func       Dr    myname1rP   123myname2targetrQ   _counter)return_value zThread-2NzThread-3r   zThread-5 (func))r)   rR   assertEqualrQ   r   patchobject)r5   ry   r   s   &  r   	test_nameThreadTests.test_name   sp   !!y1i0 !!s+e, !!I>i0ZZy*1EE%%2.FV[[*5 F ZZy*1EE%%'FV[[*5 F ZZy*1EE%%T2FV[[*;< FE FE FE FEEs$   4G62G/4HG,	/G?	H	c                t  a  ^.pR
pR.pRp^.3pR
.pVV 3R l3VV 3R l3VV 3R l3VV 3R l3VV 3R l3VV 3R l33pV F_  w  rS P                  WR7      ;_uu_ 4        \        P                  ! WR7      p
V
P                  4        V
P	                  4        R	R	R	4       Ka  	  R	#   + '       g   i     Kv  ; i)r:   strc                 (   < SP                  V ^4      # r:   r   argr5   s   &r   <lambda>0ThreadTests.test_args_argument.<locals>.<lambda>   s    4#3#3C#;r    c                 (   < SP                  V ^4      # r   r   r   s   &r   r   r      s    D$4$4S!$<r    c                 (   < SP                  V R 4      # r   r   r   s   &r   r   r      s    4#3#3C#?r    c                 (   < SP                  V R 4      # r   r   r   s   &r   r   r      s    D$4$4S%$@r    c                 *   < SP                  V ^.4      # r   r   r   s   &r   r   r      s    (8(8qc(Br    c                 (   < SP                  V R4      # )r:   r   r   r   s   &r   r   r      s    (8(8d(Cr    r   argsNr   r   )subTestr)   rR   startjoin)r5   num_list	num_tuplestr_list	str_tuplelist_in_tupletuple_in_list
test_casesr   r   ts   f          r   test_args_argumentThreadTests.test_args_argument   s     3	7	 ;<<=?@@ABCCD

 'LDV77$$F>	 87 '777s    8B&&B7c           	        \         P                  ! 4        V P                  \        \         P                  ^4       V P                  \        \         P                  ^R7       V P                  \        \         P                  ^^^^R7       R# )r:   )a)r   bN)r)   LockassertRaises	TypeErrorr4   s   &r   test_lock_no_argsThreadTests.test_lock_no_args   sZ    )Y^^Q7)Y^^q9)Y^^QQ!Dr    c                    V P                  \        4      ;_uu_ 4         ! R  R\        P                  4      pRRR4       R#   + '       g   i     R# ; i)c                       ] tR t^tRtR# )1ThreadTests.test_lock_no_subclass.<locals>.MyLockrx   NrE   rF   rG   rH   rI   rx   r    r   MyLockr      s    $r    r   N)r   r   r)   r   )r5   r   s   & r   test_lock_no_subclass!ThreadTests.test_lock_no_subclass   s0     y)).. *)))s   AA	c                p    ^ RI pV P                  \        P                  R,          VP                  4       R# r0   )typesassertIsInstancer)   r   	UnionType)r5   r   s   & r   test_lock_or_noneThreadTests.test_lock_or_none   s"    innt3U__Er    c                   ^
p\         P                  ! ^R7      p\         P                  ! 4       p\        4       p. p\	        V4       Fn  p\        RV,          WW44      pVP                  V4       V P                  VP                  4       V P                  \        V4      R4       VP                  4        Kp  	  \        \         R4      '       db   \        R V 4       4      \         P                  ! 4       0,          pV P                  RV4       V P!                  \#        V4      V^,           4       \$        '       d   \'        R4       V F  pVP)                  4        V P+                  VP-                  4       4       V P/                  VP                  ^ 4       V P1                  VP                  4       V P                  \        V4      R4       K  	  \$        '       d   \'        R	4       V P!                  VP3                  4       ^ 4       R# )

   r2   z<thread %d>z^<TestThread\(.*, initial\)>$get_native_idc              3   8   "   T F  qP                   x  K  	  R # 5irB   )	native_id).0r   s   & r   	<genexpr>/ThreadTests.test_various_ops.<locals>.<genexpr>   s     :'Q[['s   Nz!waiting for all tasks to completez#^<TestThread\(.*, stopped -?\d+\)>$zall tasks done)r)   BoundedSemaphoreRLockr.   rangerN   appendassertIsNoneidentassertRegexreprr   hasattrsetr   assertNotInr   lenr   r[   r   assertFalseis_aliveassertNotEqualassertIsNotNonerC   )	r5   NUMTASKSrS   rT   
numrunningthreadsir   
native_idss	   &        r   test_various_opsThreadTests.test_various_ops   s~     ))2!Y
xA=?DJANN1agg&T!W&FGGGI ! 9o..:'::i>U>U>W=XXJT:.S_hl;756AFFHQZZ\*+  )T!W&LM  7"#)1-r    c                  aa V P                  \        P                  ! 4       P                  4       VV3R  lp\        P                  ! 4       o. o\
        P                  ! 4       ;_uu_ 4        \        P                  ! VR4      pSP                  4        V P                  S^ ,          V4       RRR4       R#   + '       g   i     R# ; i)c                     < SP                  \        P                  ! 4       P                  4       S P	                  4        R # rB   )r   r)   current_threadr   r   )rY   r   s   r   f9ThreadTests.test_ident_of_no_threading_threads.<locals>.f   s'    LL11399:HHJr    Nrx   )r   r)   r   r   Eventr   wait_threads_exit_threadstart_new_threadwaitr   )r5   r   tidrY   r   s   &  @@r   "test_ident_of_no_threading_threads.ThreadTests.test_ident_of_no_threading_threads   s    Y557==>	  //11**1b1CIIKU1Xs+ 2111s   ,AB77C	c                   \         '       d   \        R 4        \        P                  ! R4       T P                  4        \        P                  ! ^ 4       R#   \        P
                   d    \        P                  ! R4      hi ; i)z!with 256 KiB thread stack size...i   4platform does not support changing thread stack sizeN	r   r[   r)   
stack_sizer   errorr   SkipTestr   r4   s   &r   test_various_ops_small_stack(ThreadTests.test_various_ops_small_stack   so    756	H  ( 	Q	 }} 	H##FH H	H   A ,Bc                   \         '       d   \        R 4        \        P                  ! R4       T P                  4        \        P                  ! ^ 4       R#   \        P
                   d    \        P                  ! R4      hi ; i)zwith 1 MiB thread stack size...i   r   Nr   r4   s   &r   test_various_ops_large_stack(ThreadTests.test_various_ops_large_stack  so    734	H  * 	Q	 }} 	H##FH H	Hr   c                  a aa R oR oVVV 3R lp\         P                  ! 4       pVP                  4        \        P                  ! 4       ;_uu_ 4        \
        P                  ! W34      pVP                  4        R R R 4       Se   ShS P                  XSP                  4       S P                  \        4      ;_uu_ 4        SP                  4        R R R 4       SP                  P                  4        S P                  \        4      ;_uu_ 4        SP                  4        R R R 4       ^p\        P                   ! 4       V,           p\        P                   ! 4       V8  dH   \         P"                  P%                  SP                  4      SJd   R # \        P&                  ! R4       Ka  S P)                  R4       R #   + '       g   i     ELK; i  + '       g   i     EL; i  + '       g   i     L; i)Nc                   <  \         P                  ! 4       oSP                  pSP                  V\         P                  4       SP                  S\         P                  4       SP                  \         P                  P                  V4      S4       SP                  SP                  4       R 4       SP                  R\        S4      4       V P                  4        R#   \         d   pTo Rp?L$Rp?ii ; i  T P                  4        i ; i)z-Expected _DummyThread to be considered alive._DummyThreadN)r)   r   r   assertIn_activer   r   assertIsrC   
assertTruer   r   BaseExceptionrelease)rT   r   edummy_threadr   r5   s   &  r   r   *ThreadTests.test_foreign_thread.<locals>.f  s     
  )779"((c9#4#45%%lI4J4JKi//33C8,G ))+C nd<.@A  !  s*   CC   C7+C2-C: 2C77C: :D皙?z[It was expected that the created threading._DummyThread was removed from threading._active.)r)   r   acquirer   r   r   r   r   r   r   RuntimeErrorr   _startedclearr   r]   	monotonicr   rC   r^   fail)r5   r   rT   r   timeout
timeout_atr   r   s   f     @@r   test_foreign_threadThreadTests.test_foreign_thread  sS   	 ,  //11**1h7CMMO 2 Kl001|,, -##%|,,!!# - ^^%/
nn+  $$\%7%78LJJrNIIst- 211 -,, -,s$   (F<GG$<G	G!	$G4	c                  a	a
a \        R 4      pVP                  P                  pVP                  VP                  3Vn         ! R R\        4      o	VP	                  S	4      p\        P                  ! 4       pV P                  V\        4       V P                  V^ 4        V! WC4      p K    S	 d     Mi ; i T P                  X^4       M  \         d     Mi ; i\        P                  ! 4       o\        P                  ! 4       o
 ! T	T
T3R lR\        P                   4      pT! 4       pRTn        TP%                  4        \&        '       d   \)        R4       \&        '       d   \)        R4       T! RT4      pT P                  T^ 4       \&        '       d   \)        R4       SP+                  4       pT P-                  T4       \&        '       d   \)        R	4       T P/                  TP0                  4       \&        '       d   \)        R
4       T! TP2                  T4      pT P                  T^4       \&        '       d   \)        R4       S
P+                  \4        P6                  R7       T P-                  TP0                  4       \&        '       d   \)        R4       TP0                  '       d   TP9                  4        R# R# )ctypesc                       ] tR tRtRtR# )<ThreadTests.test_PyThreadState_SetAsyncExc.<locals>.AsyncExciL  rx   Nr   rx   r    r   AsyncExcr  L  s    r    r  Tc                   2   <a  ] tR tRt o VVV3R ltRtV tR# ):ThreadTests.test_PyThreadState_SetAsyncExc.<locals>.Workerio  c                   < \         P                  ! 4       V n        R V n          SP	                  4        \
        P                  ! R4       K)    S d    RT n        SP	                  4         R# i ; i)FTr  N)r)   	get_identidfinishedr   r]   r^   )r5   r  worker_saw_exceptionworker_starteds   &r   ra   >ThreadTests.test_PyThreadState_SetAsyncExc.<locals>.Worker.runp  s[    #--/ %/&**,

3 /$(DM(,,./s   )A A/.A/)r  r  NrE   rF   rG   rH   ra   rI   rJ   )rL   r  r  r  s   @r   Workerr  o  s     
/ 
/r    r  z    started worker threadz     trying nonsensical thread idz,    waiting for worker thread to get startedz"    verifying worker hasn't exitedz2    attempting to raise asynch exception in workerz5    waiting for worker to say it caught the exceptionr  z    all OK -- joining workerN)r	   	pythonapiPyThreadState_SetAsyncExcc_ulong	py_objectargtypes	Exceptionr)   r  r   intassertGreaterr  r   UnboundLocalErrorr   rR   daemonr   r   r[   r   r   r   r  r  r   SHORT_TIMEOUTr   )r5   r  set_async_exc	exceptionr   resultr  r   retr  r  r  s   &        @@@r   test_PyThreadState_SetAsyncExc*ThreadTests.test_PyThreadState_SetAsyncExcF  s*   x(((BB"(..&2B2B!C	y 	 $$X.	 !!#c3'3"	-"32F  			VQ'  		 #*(0	/ 	/Y%% 	/ H		7-. 745r9-# 7@A!!#767$7FGqttY/#7IJ!!'*?*?!@

#701:::FFH s$    B+ +B54B59C CCc                D   R  p\         P                  pV\         n         \         P                  ! R R7      pV P                  \         P                  VP
                  4       V P                  V\         P                  9   R4       V\         n        R#   T\         n        i ; i)c                  ,    \         P                  ! 4       hrB   )r)   ThreadErrorr   kwargss   *,r   fail_new_thread7ThreadTests.test_limbo_cleanup.<locals>.fail_new_thread  s    ''))r    c                      R # rB   rx   rx   r    r   r   0ThreadTests.test_limbo_cleanup.<locals>.<lambda>      r    r   z:Failed to cleanup _limbo map on failure of Thread.start().N)r)   _start_joinable_threadrR   r   r1  r   r   _limbo)r5   r4  r9  r   s   &   r   test_limbo_cleanupThreadTests.test_limbo_cleanup  s    	*!*!A!A+:	(	F  5Ai33QWW=Y%%%LN 0FI,/EI,s   A%B Bc                    \         P                  ! R R7      '       d   V P                  R4       \        R4       \	        RR4      w  rpV P                  V^*4       R# )Tr   TSAN would report thread leakr  -caN  if 1:
            import ctypes, sys, time, _thread

            # This lock is used as a simple event variable.
            ready = _thread.allocate_lock()
            ready.acquire()

            # Module globals are cleared before __del__ is run
            # So we save the functions in class dict
            class C:
                ensure = ctypes.pythonapi.PyGILState_Ensure
                release = ctypes.pythonapi.PyGILState_Release
                def __del__(self):
                    state = self.ensure()
                    self.release(state)

            def waitingThread():
                x = C()
                ready.release()
                time.sleep(100)

            _thread.start_new_thread(waitingThread, ())
            ready.acquire()  # Be sure the other thread is waiting.
            sys.exit(42)
            N)r   r   skipTestr	   r   r   r5   rcouterrs   &   r   test_finalize_running_thread(ThreadTests.test_finalize_running_thread  sS     ""$// MM9:h,T 4 2 	R r    c                z    \         P                  ! R R7      '       d   V P                  R4       \        RR4       R# )Tr   r>  r?  aP  if 1:
            import sys, threading

            # A deadlock-killer, to prevent the
            # testsuite to hang forever
            def killer():
                import os, time
                time.sleep(2)
                print('program blocked; aborting')
                os._exit(2)
            t = threading.Thread(target=killer)
            t.daemon = True
            t.start()

            # This is the trace function
            def func(frame, event, arg):
                threading.current_thread()
                return func

            sys.settrace(func)
            N)r   r   r@  r
   r4   s   &r   test_finalize_with_trace$ThreadTests.test_finalize_with_trace  s3     ""$// MM9:   	r    c                    \        R R4      w  rpV P                  VP                  4       R4       V P                  VR4       R# )r?  a  if 1:
                import threading
                from time import sleep

                def child():
                    sleep(1)
                    # As a non-daemon thread we SHOULD wake up and nothing
                    # should be torn down yet
                    print("Woke up, sleep function is:", sleep)

                threading.Thread(target=child).start()
                raise SystemExit
            s5   Woke up, sleep function is: <built-in function sleep>r    Nr
   r   striprA  s   &   r   test_join_nondaemon_on_shutdown+ThreadTests.test_join_nondaemon_on_shutdown  sE     ( /  	D	Fc"r    c                   \         P                  p\        P                  ! 4       p \	        ^^d4       Fy  p\
        P                  ! VR,          4       \         P                  ! R R7      pVP                  4        VP                  4        V! 4       pV P                  WERW53,          4       K{  	  \        P                  ! V4       R#   \        P                  ! T4       i ; i)r:   g-C6*?c                      R # rB   rx   rx   r    r   r   7ThreadTests.test_enumerate_after_join.<locals>.<lambda>  s    Dr    r   z&#1703448 triggered after %d trials: %sN)r)   	enumerater   getswitchintervalr   r   setswitchintervalrR   r   r   r   )r5   enumold_intervalr   r   ls   &     r   test_enumerate_after_join%ThreadTests.test_enumerate_after_join  s     "",,.
	01c]))!f*5$$L9	F  <vEG # !!,/C!!,/s   B	C C Fsizememusedry_runc           	       a . oR  pV3R lp\        ^^4       F  p\        P                  ! VR7      .p\        V4       F2  pVP                  \        P                  ! VV^ ,          3R7      4       K4  	  V F  pVP	                  4        K  	  \
        P                  ! R4       V F  pVP                  4        K  	  S'       g   K  S^ ,          h	  R# )c                  2    \         P                  ! R 4       R# )g{Gzt?Nr]   r^   rx   r    r   worker;ThreadTests.test_join_from_multiple_threads.<locals>.worker  s    JJur    c                 ~   <  V P                  4        R #   \         d   pSP                  T4        R p?R # R p?ii ; irB   )r   r#  r   )r   r   errorss   & r   joiner;ThreadTests.test_join_from_multiple_threads.<locals>.joiner  s0    ! !a  !s    <7<r   r   {Gz?N)r   r)   rR   r   r   r]   r^   r   )	r5   r[  ra  re  Nr   r   r   rd  s	   &&      @r   test_join_from_multiple_threads+ThreadTests.test_join_from_multiple_threads  s     		! q"A ''v67G1Xy//v6=aj] D E  	 JJt vQi r    c                p  a \         P                  ! 4       oSP                  4        V3R  lp\        P                  ! VR7      pVP                  4        VP                  RR7       VP                  4       '       g   Q hSP                  4        VP                  4        VP                  4       '       d   Q hR# )c                  (   < S P                  4        R # rB   )r  )locks   r   ra  2ThreadTests.test_join_with_timeout.<locals>.worker4  s    LLNr    r   rg  r  N)	r   allocate_lockr  r)   rR   r   r   r   r   )r5   ra  r   rm  s   &  @r   test_join_with_timeout"ThreadTests.test_join_with_timeout0  s    $$&	 !!0D!    ??$$$$$r    c                    ! R  R\         4      p\        V 4       V! RR7      p\        P                  ! V4      pVP                  P                  4        ?V P                  V! 4       R\        P                  ! V! 4       4      ,          R7       V! RR7      p\        P                  ! V4      pVP                  P                  4        ?V P                  V! 4       R\        P                  ! V! 4       4      ,          R7       R# )c                   ,   a  ] tR tRt o R tR tRtV tR# )DThreadTests.test_no_refcycle_through_target.<locals>.RunSelfFunctioni@  c                    Wn         \        P                  ! V P                  V 3R V /R7      V n        V P                  P                  4        R# )yet_another)r   r   r3  N)should_raiser)   rR   _runr   r   )r5   rw  s   &&r   r6   MThreadTests.test_no_refcycle_through_target.<locals>.RunSelfFunction.__init__A  sB     %1!'..dii59G7DT6JL !!#r    c                6    V P                   '       d   \        hR # rB   )rw  
SystemExit)r5   	other_refrv  s   &&&r   rx  IThreadTests.test_no_refcycle_through_target.<locals>.RunSelfFunction._runJ  s    $$$$$ %r    )rw  r   N)rE   rF   rG   rH   r6   rx  rI   rJ   rK   s   @r   RunSelfFunctionrt  @  s     $% %r    r~  F)rw  z%d references still around)msgTN)	r   r,   weakrefrefr   r   r   r   getrefcount)r5   r~  cyclic_objectweak_cyclic_objectraising_cyclic_objectweak_raising_cyclic_objects   &     r   test_no_refcycle_through_target+ThreadTests.test_no_refcycle_through_target?  s    	%f 	% 	#4('U;$[[7!!#,.:!oo.@.BCD 	 	F !0T B%,[[1F%G"$$))+!46:!oo.H.JKL 	 	Nr    c                h   \         P                  ! 4       pV P                  \        R 4      ;_uu_ 4        VP	                  4        RRR4       V P                  \        R4      ;_uu_ 4        VP                  R4       RRR4       V P                  \        R4      ;_uu_ 4        VP                  4        RRR4       V P                  \        R4      ;_uu_ 4        VP                  R4       RRR4       \         P                  ! 4       pV P                  \        R4      ;_uu_ 4        VP                  4        RRR4       \         P                  ! 4       pVP                  4        V P                  \        R4      ;_uu_ 4        VP                  4        RRR4       V P                  \        R	4      ;_uu_ 4        \         P                  ! 4        RRR4       V P                  \        R
4      ;_uu_ 4        \         P                  ! 4        RRR4       R#   + '       g   i     EL; i  + '       g   i     EL; i  + '       g   i     EL; i  + '       g   i     ELo; i  + '       g   i     EL7; i  + '       g   i     L; i  + '       g   i     L; i  + '       g   i     R# ; i)zget the daemon attributeNzset the daemon attributeTzget the name attributezset the name attributerQ   zuse is_set()zuse notify_all()zuse active_count()zuse current_thread())r)   rR   assertWarnsRegexDeprecationWarningisDaemon	setDaemongetNamesetNamer   isSet	Conditionr  	notifyAllactiveCountcurrentThread)r5   r   r   conds   &   r   test_old_threading_api"ThreadTests.test_old_threading_api`  s    ""#5#>@ @JJL@ ""#5#>@ @KK@ ""#5#<> >IIK> ""#5#<> >IIf> OO""#5~FFGGI G ""$""#57IJJNN K ""#57KLL!!# M""#57MNN##% ON1@ @ @@ @ @> > >> > >
 GFF
 KJ MLNNNs_   H+H*#H>I'I&I::J6J H'	*H;	>I	I#	&I7	:J
	J	 J1	c                    \         P                  ! 4       pV P                  R \        V4      4       RVn        V P                  R \        V4      4       R# r'  TN)r)   rR   r   r   r'  r   r5   r   s   & r   test_repr_daemonThreadTests.test_repr_daemon  s=    47+hQ(r    c                .   \         P                  ! 4       pV P                  VP                  4       \         P                  ! R R7      pV P                  VP                  4       \         P                  ! RR7      pV P	                  VP                  4       R# )F)r'  TN)r)   rR   r   r'  r   r  s   & r   test_daemon_paramThreadTests.test_daemon_param  sd    "E*"D)!r    c                p    R p\        RV4      w  r#pV P                  VR4       V P                  VR4       R# )a  if 1:
            import _thread, threading, os, time, warnings

            def background_thread(evt):
                # Creates and registers the _DummyThread instance
                threading.current_thread()
                evt.set()
                time.sleep(10)

            evt = threading.Event()
            _thread.start_new_thread(background_thread, (evt,))
            evt.wait()
            assert threading.active_count() == 2, threading.active_count()
            with warnings.catch_warnings(record=True) as ws:
                warnings.filterwarnings(
                        "always", category=DeprecationWarning)
                if os.fork() == 0:
                    assert threading.active_count() == 1, threading.active_count()
                    os._exit(0)
                else:
                    assert ws[0].category == DeprecationWarning, ws[0]
                    assert 'fork' in str(ws[0].message), ws[0]
                    os.wait()
        r?  r    Nr
   r   r5   code_rC  rD  s   &    r   test_dummy_thread_after_fork(ThreadTests.test_dummy_thread_after_fork  s;    0 'tT2c"c"r    c                   \         P                  ! 4       pV P                  \         P                  V4       \        P
                  P                  R 4       \        ^4       F  p\        P                  ! R R7      pVP                  4        \        P                  ! \        RR7      ;_uu_ 4        \        P                  ! 4       ;p^ 8X  d0   \        P                  ! VP!                  4       '       d   ^M^
4       M(VP#                  4        \
        P$                  ! V^
R7       RRR4       K  	  R#   + '       g   i     K  ; i)gư>c                      R # rB   rx   rx   r    r   r   6ThreadTests.test_is_alive_after_fork.<locals>.<lambda>  r8  r    r   ignorecategoryactionexitcodeN)r   rS  r'   rT  r   r   r   r)   rR   r   rs   catch_warningsr  osfork_exitr   r   wait_process)r5   rV  r   r   pids   &    r   test_is_alive_after_fork$ThreadTests.test_is_alive_after_fork  s     ,,.--|< 	&&t,rA  5AGGI((2D08: :779$C*HH1::<<RR8FFH((r:: :	 : : :s   /AD121D11Ec                  a  \         P                  ! 4       pS P                  VP                  R 4       S P                  VP                  \         P
                  ! 4       P                  4       S P                  VP                  \         P                  ! 4       4       V 3R lp\         P                  ! VR7      pVP                  4        VP                  4        R# )
MainThreadc                     < S P                  \        P                  ! 4       P                  \        P                  ! 4       P                  4       R # rB   )r   r)   main_threadr   r   r4   s   r   r   'ThreadTests.test_main_thread.<locals>.f  s5    	 5 5 7 = = ) 8 8 : @ @Br    r   N)
r)   r  r   rQ   r   r   r  rR   r   r   )r5   mainr   ths   f   r   test_main_threadThreadTests.test_main_thread  s    $$&L1Y%=%=%?%E%EFY%8%8%:;	B Q'


	r    waitpidztest needs os.waitpid()c                    R p\        RV4      w  r#pVP                  4       P                  RR4      pV P                  VR4       V P                  VR4       R# )a!  if 1:
            import os, threading
            from test import support

            ident = threading.get_ident()
            pid = os.fork()
            if pid == 0:
                print("current ident", threading.get_ident() == ident)
                main = threading.main_thread()
                print("main", main.name)
                print("main ident", main.ident == ident)
                print("current is main", threading.current_thread() is main)
            else:
                support.wait_process(pid, exitcode=0)
        r?  r   r    zHcurrent ident True
main MainThread
main ident True
current is main True
Nr
   decodereplacer   r5   r  r  rC  rD  datas   &     r   test_main_thread_after_fork'ThreadTests.test_main_thread_after_fork  sX     'tT2zz|##D"-c"2	3r    c                    R p\        RV4      w  r#pVP                  4       P                  RR4      pV P                  VP                  R4      R4       V P                  VR4       R# )a  if 1:
            import os, threading, sys, warnings
            from test import support

            def func():
                ident = threading.get_ident()
                with warnings.catch_warnings(record=True) as ws:
                    warnings.filterwarnings(
                            "always", category=DeprecationWarning)
                    pid = os.fork()
                    if pid == 0:
                        print("current ident", threading.get_ident() == ident)
                        main = threading.main_thread()
                        print("main", main.name, type(main).__name__)
                        print("main ident", main.ident == ident)
                        print("current is main", threading.current_thread() is main)
                        # stdout is fully buffered because not a tty,
                        # we have to flush before exit.
                        sys.stdout.flush()
                    else:
                        assert ws[0].category == DeprecationWarning, ws[0]
                        assert 'fork' in str(ws[0].message), ws[0]
                        support.wait_process(pid, exitcode=0)

            th = threading.Thread(target=func)
            th.start()
            th.join()
        r?  r  r   utf-8zTcurrent ident True
main Thread-1 (func) Thread
main ident True
current is main True
Nr  r  s   &     r   /test_main_thread_after_fork_from_nonmain_thread;ThreadTests.test_main_thread_after_fork_from_nonmain_thread  sa    8 'tT2zz|##D"-G,b12	r    c                   R V,          p\        RRRV4      w  r4pVP                  4       P                  RR4      pV P                  VP                  4       R4       T P                  TV'       d   RMRRV: R2,           R	,           4       R
# )aC  if 1:
            import os, threading, sys, traceback, _thread
            from test import support

            def func(lock):
                ident = threading.get_ident()
                if %s:
                    # call current_thread() before fork to allocate DummyThread
                    current = threading.current_thread()
                    print("current", current.name, type(current).__name__)
                print("ident in _active", ident in threading._active)
                # flush before fork, so child won't flush it again
                sys.stdout.flush()
                pid = os.fork()
                if pid == 0:
                    print("current ident", threading.get_ident() == ident)
                    main = threading.main_thread()
                    print("main", main.name, type(main).__name__)
                    print("main ident", main.ident == ident)
                    print("current is main", threading.current_thread() is main)
                    print("_dangling", [t.name for t in list(threading._dangling)])
                    # stdout is fully buffered because not a tty,
                    # we have to flush before exit.
                    sys.stdout.flush()
                    try:
                        threading._shutdown()
                        os._exit(0)
                    except:
                        traceback.print_exc()
                        sys.stderr.flush()
                        os._exit(1)
                else:
                    try:
                        support.wait_process(pid, exitcode=0)
                    except Exception:
                        # avoid 'could not acquire lock for
                        # <_io.BufferedWriter name='<stderr>'> at interpreter shutdown,'
                        traceback.print_exc()
                        sys.stderr.flush()
                    finally:
                        lock.release()

            join_lock = _thread.allocate_lock()
            join_lock.acquire()
            th = _thread.start_new_thread(func, (join_lock,))
            join_lock.acquire()
        z-Wzignore::DeprecationWarningr?  r  r   zcurrent Dummy-1 _DummyThread
zident in _active 
zmcurrent ident True
main MainThread _MainThread
main ident True
current is main True
_dangling ['MainThread']
Nr  )r5   create_dummyr  r  rC  rD  r  s   &&     r   /test_main_thread_after_fork_from_foreign_thread;ThreadTests.test_main_thread_after_fork_from_foreign_thread  s    .\ ].b 't-I4QUVzz|##D"-r*>J:PR,\,<B?@66	7r    c                *    V P                  R R7       R# )T)r  N)r  )r5   r  s   &&r   -test_main_thread_after_fork_from_dummy_thread9ThreadTests.test_main_thread_after_fork_from_dummy_threadU  s    <<$<Or    c                    R p\        RV4      w  r#pVP                  4       pV P                  VR4       V P                  VP                  4       R.^,          4       R# )a  if 1:
            import gc, threading

            main_thread = threading.current_thread()
            assert main_thread is threading.main_thread()  # sanity check

            class RefCycle:
                def __init__(self):
                    self.cycle = self

                def __del__(self):
                    print("GC:",
                          threading.current_thread() is main_thread,
                          threading.main_thread() is main_thread,
                          threading.enumerate() == [main_thread])

            RefCycle()
            gc.collect()  # sanity check
            x = RefCycle()
        r?  r    zGC: True True TrueN)r
   r  r   
splitlinesr  s   &     r    test_main_thread_during_shutdown,ThreadTests.test_main_thread_during_shutdownX  sX    ( 'tT2zz|c"*./!3	5r    c                L    R p\        RV4      w  r#pV P                  VR4       R# )a  if 1:
            import os
            import threading
            import time
            import random

            def random_sleep():
                seconds = random.random() * 0.010
                time.sleep(seconds)

            class Sleeper:
                def __del__(self):
                    random_sleep()

            tls = threading.local()

            def f():
                # Sleep a bit so that the thread is still running when
                # Py_Finalize() is called.
                random_sleep()
                tls.x = Sleeper()
                random_sleep()

            threading.Thread(target=f).start()
            random_sleep()
        r?  r    Nr  r5   r  rB  rC  rD  s   &    r   test_finalization_shutdown&ThreadTests.test_finalization_shutdownu  s+    4 (d3c"r    c                >  aa \         P                  ! 4       o\         P                  ! 4       oSP                  4        SP                  4        VV3R  lp\        P                  ! VR7      pVP                  4        SP                  4        V P                  R\        V4      4       SP                  4        Rp\        R4       F+  pV\        V4      9   d    M\        P                  ! R4       K-  	  V P                  V\        V4      4       VP                  4        R# )c                  H   < SP                  4        S P                  4        R # rB   )r   r  )finishstarteds   r   r   (ThreadTests.test_repr_stopped.<locals>.f  s    OONNr    r   r  stoppedi  rg  N)r   ro  r  r)   rR   r   r   r   r   r   r]   r^   r   )r5   r   r   LOOKING_FORr   r  r  s   &    @@r   test_repr_stoppedThreadTests.test_repr_stopped  s    '')&&(	 A&		ia)  sAd1g%JJt  	k47+	r    c                \   \        ^^
4       EF  p\        P                  ! V4      p\        V4       Uu. uF$  p\        P                  ! VP                  R7      NK&  	  ppV F  pVP                  4        K  	  V F  pVP                  4        K  	  \        V4       Uu. uF$  p\        P                  ! VP                  R7      NK&  	  ppV F  pVP                  4        K  	  V F  pVP                  4        K  	  V P                  \        VP                  4       EK  	  R# u upi u upi )r:   r   N)
r   r)   r   rR   r  r   r   r   r   
ValueError)r5   limitbsr  r   r   s   &     r   test_BoundedSemaphore_limit'ThreadTests.test_BoundedSemaphore_limit  s    1b\E++E2B %e. ,1 !''rzz: ,  .	   !&e. ,1 !''rzz: ,  .	  j"**5 "..s   *D$*D)c                  aaa \        R 4      pV3R loR oVV3R loRSn        \        P                  ! 4       p\        P                  ! S4        \
        P                  ! S4       VP                  S4       \        ^4       F
  pS! 4        K  	  \        P                  ! V4       \
        P                  ! V4       R#   \        P                  ! T4       \
        P                  ! T4       i ; i)	_testcapic                    < S# rB   rx   frameeventr   
noop_traces   &&&r   r  9ThreadTests.test_frame_tstate_tracing.<locals>.noop_trace  	    r    c               3      "    Rx  K  5i)r:   	generatorrx   rx   r    r   r  8ThreadTests.test_frame_tstate_tracing.<locals>.generator  s     !!s   
c                  b   < S P                   f   S! 4       S n         \        S P                   4      # rB   )gennext)callbackr  s   r   r  7ThreadTests.test_frame_tstate_tracing.<locals>.callback  s%    ||#({%%r    N)r	   r  r   gettracesettracer)   call_in_temporary_c_threadr   )r5   r  	old_tracer   r  r  r  s   &   @@@r   test_frame_tstate_tracing%ThreadTests.test_frame_tstate_tracing  s    !+.			"	& LLN	Z 	*z* 00: a
 ! LL#y) LL#y)s   A C   .C.c                  a V3R  lo\         P                  ! 4       p \         P                  ! S4       \         P                  ! 4       pV P                  SV4       \         P                  ! V4       R#   \         P                  ! T4       i ; i)c                    < S# rB   rx   r  s   &&&r   r  -ThreadTests.test_gettrace.<locals>.noop_trace  r  r    N)r)   r  r   r   )r5   r  
trace_funcr  s   &  @r   test_gettraceThreadTests.test_gettrace  sf    	 &&(		*z*"++-JZ
3y)Iy)s   =A3 3Bc                2  aaa R  p\         P                  ! 4       p\         P                  ! 4       o\         P                  ! 4       o. oVVV3R lp \         P                  ! VR7      pVP	                  4        SP                  4        \         P                  ! V4       SP                  4        VP                  4        V P                  SRV.4       V P                  \         P                  ! 4       V4       V P                  \        P                  ! 4       V4       \         P                  ! V4       V P                  \         P                  ! 4       V4       V P                  \        P                  ! 4       V4       R#   \         P                  ! T4       i ; i)c                      R # rB   rx   r   s   *r   fn1ThreadTests.test_gettrace_all_threads.<locals>.fn      tr    c                     < SP                  \        P                  ! 4       4       S P                  4        SP	                  4        SP                  \        P                  ! 4       4       R # rB   )r   r   r  r   r   )first_checksecond_checktrace_funcss   r   checker6ThreadTests.test_gettrace_all_threads.<locals>.checker  sA    s||~.OOs||~.r    r   N)r)   r  r   rR   r   r   settrace_all_threadsr   r   r   r   )r5   r  r  r  r   r  r  r  s   &    @@@r   test_gettrace_all_threads%ThreadTests.test_gettrace_all_threads  s   &&(	oo' (	/	6  0AGGI**2.FFH[4*5Y//126S\\^R0**95++-y93 **95   CE> >Fc                   R  p\         P                  ! 4       p \         P                  ! V4       V P                  V\         P                  ! 4       4       \         P                  ! V4       R#   \         P                  ! T4       i ; i)c                      R # rB   rx   r  s   *r   r  'ThreadTests.test_getprofile.<locals>.fn  r  r    N)r)   
getprofile
setprofiler   )r5   r  old_profiles   &  r   test_getprofileThreadTests.test_getprofile  s\    **,	.  $R!5!5!78  -I  -s   ;A- -Bc                2  aaa R  p\         P                  ! 4       p\         P                  ! 4       o\         P                  ! 4       o. oVVV3R lp \         P                  ! VR7      pVP	                  4        SP                  4        \         P                  ! V4       SP                  4        VP                  4        V P                  SRV.4       V P                  \         P                  ! 4       V4       V P                  \        P                  ! 4       V4       \         P                  ! V4       V P                  \         P                  ! 4       V4       V P                  \        P                  ! 4       V4       R#   \         P                  ! T4       i ; i)c                      R # rB   rx   r  s   *r   r  3ThreadTests.test_getprofile_all_threads.<locals>.fn!  r  r    c                     < SP                  \        P                  ! 4       4       S P                  4        SP	                  4        SP                  \        P                  ! 4       4       R # rB   )r   r   r  r   r   )r  profile_funcsr  s   r   r  8ThreadTests.test_getprofile_all_threads.<locals>.checker'  sC      !12OO  !12r    r   N)r)   r  r   rR   r   r   setprofile_all_threadsr   r   r   r   )r5   r  r   r  r   r  r'  r  s   &    @@@r   test_getprofile_all_threads'ThreadTests.test_getprofile_all_threads   s   **,oo' (	3	:  0AGGI,,R0FFH]T2J7Y113R8S^^-r2,,[9--/=);7 ,,[9r  c                d    \        R R4      w  rpV P                  VP                  4       R4       R# )r?  a(  if 1:
            import threading

            class Atexit:
                def __del__(self):
                    print("thread_dict.atexit = %r" % thread_dict.atexit)

            thread_dict = threading.local()
            thread_dict.atexit = "value"

            atexit = Atexit()
        s   thread_dict.atexit = 'value'N)r
   r   rstriprA  s   &   r   test_locals_at_exitThreadTests.test_locals_at_exit=  s2     ( /  	'FGr    c                     ! R  R\         4      pV! 4       p\        P                  ! VR7      pVP                  4        VP	                  4        V P                  VP                  4       R# )c                   2   a  ] tR tRt o R tR tR tRtV tR# )6ThreadTests.test_boolean_target.<locals>.BooleanTargetiS  c                    R V n         R# )FNranr4   s   &r   r6   ?ThreadTests.test_boolean_target.<locals>.BooleanTarget.__init__T  s	     r    c                    R # Frx   r4   s   &r   __bool__?ThreadTests.test_boolean_target.<locals>.BooleanTarget.__bool__V  s    r    c                    R V n         R# )TNr4  r4   s   &r   __call__?ThreadTests.test_boolean_target.<locals>.BooleanTarget.__call__X  s	    r    r4  N)	rE   rF   rG   rH   r6   r9  r<  rI   rJ   rK   s   @r   BooleanTargetr2  S  s     !   r    r>  r   N)r   r)   rR   r   r   r   r5  )r5   r>  r   r   s   &   r   test_boolean_targetThreadTests.test_boolean_targetN  sI    
	 F 	  !!0

#r    c                    R  p\         P                  ! 4       ;_uu_ 4        \        P                  ! VR7      P	                  4        RRR4       R#   + '       g   i     R# ; i)c                      R # rB   rx   rx   r    r   noop0ThreadTests.test_leak_without_join.<locals>.noopd  r{   r    r   N)r   r   r)   rR   r   )r5   rC  s   & r   test_leak_without_join"ThreadTests.test_leak_without_joina  s<     	//11D)//1 2111s   &AA"	c                    \         P                  ! R 4      p\        RV4      w  r#pV P                  VR4       V P                  VR4       R# )a  
            import _thread
            import sys

            event = _thread.allocate_lock()
            event.acquire()

            def import_threading():
                import threading
                event.release()

            if 'threading' in sys.modules:
                raise Exception('threading is already imported')

            _thread.start_new_thread(import_threading, ())

            # wait until the threading module is imported
            event.acquire()
            event.release()

            if 'threading' not in sys.modules:
                raise Exception('threading is not imported')

            # don't wait until the thread completes
        r?  r    N)textwrapdedentr
   r   r  s   &    r   test_import_from_another_thread+ThreadTests.test_import_from_another_threadi  sI        2 (d3c"c"r    c                    R p\        RV4      w  r#pV P                  VP                  4       R4       V P                  RV4       R# )a6  if 1:
            import _thread

            def f():
                print("shouldn't be printed")

            class AtFinalization:
                def __del__(self):
                    print("OK")
                    _thread.start_new_thread(f, ())
            at_finalization = AtFinalization()
        r?     OKs/   can't create new thread at interpreter shutdownN)r
   r   rL  r   r  s   &    r   %test_start_new_thread_at_finalization1ThreadTests.test_start_new_thread_at_finalization  s@     'tT2e,H#Nr    c                    R Fs  pV P                  VR7      ;_uu_ 4        \        P                  ! RV R24      p\        RV4      w  r4pV P	                  VR4       V P                  RV4       R R R 4       Ku  	  R #   + '       g   i     K  ; i)Nr  ag  
                    import threading


                    def loop():
                        while True:
                            pass


                    class Cycle:
                        def __init__(self):
                            self.self_ref = self
                            self.thr = threading.Thread(
                                target=loop, daemon=True)
                            self.thr.start()

                        def __del__(self):
                            assert self.thr.is_alive()
                            try:
                                self.thr.join(timeout=a  )
                            except PythonFinalizationError:
                                assert self.thr.is_alive()
                                print('got the correct exception!')

                    # Cycle holds a reference to itself, which ensures it is
                    # cleaned up during the GC that runs after daemon threads
                    # have been forced to exit during finalization.
                    Cycle()
                r?  r    s   got the correct exception)Nr   )r   rH  rI  r
   r   r   )r5   r  r  rB  rC  rD  s   &     r   'test_join_daemon_thread_in_finalization3ThreadTests.test_join_daemon_thread_in_finalization  s     "Gg.. ,7& 8?i 	@'( :  0d;  c*:C@A /. "...s   AA<<Bc                    \         P                  ! R 4      p\        RV4      w  r#pV P                  VR4       V P	                  RV4       R# )a  
            import threading
            done = threading.Event()

            def set_event():
                done.set()

            class Cycle:
                def __init__(self):
                    self.self_ref = self
                    self.thr = threading.Thread(target=set_event, daemon=True)
                    self.thr.start()
                    self.thr.join()

                def __del__(self):
                    assert done.is_set()
                    assert not self.thr.is_alive()
                    self.thr.join()
                    assert not self.thr.is_alive()
                    print('all clear!')

            Cycle()
        r?  r    s	   all clearN)rH  rI  r
   r   r   r  s   &    r   0test_join_finished_daemon_thread_in_finalization<ThreadTests.test_join_finished_daemon_thread_in_finalization  sG        . (d3c"lC(r    c                &    ^ RI HpHp Rp\        RRV4      w  rVpVP                  4       pRV9   d   V P	                  R4       V P                  VR4       V P                  VR	4       R#   \         d   pT P	                  T4        Rp?LRp?ii ; i)
r1   )	setrlimitRLIMIT_NPROCNa  if 1:
            import resource
            import _thread

            def f():
                print("shouldn't be printed")

            limits = resource.getrlimit(resource.RLIMIT_NPROC)
            [_, hard] = limits
            resource.setrlimit(resource.RLIMIT_NPROC, (0, hard))

            try:
                handle = _thread.start_joinable_thread(f)
            except RuntimeError:
                print('ok')
            else:
                print('!skip!')
                handle.join()
        z-ur?  s   !skip!z.RLIMIT_NPROC had no effect; probably superusers   okr    )resourcerW  rX  ImportErrorr@  r
   rL  r   )r5   rW  rX  rD  r  r  rC  s   &      r   test_start_new_thread_failed(ThreadTests.test_start_new_thread_failed  s    
	8& 'tT48iikMMJKe$c"5  	MM#	s   A* *B5BBc                    \         P                  ! R R R7      '       d   V P                  R4       \        P                  ! R4      p\        RV4       R# )T)r   memoryz\https://github.com/python/cpython/issues/124878 - Known race condition that TSAN identifies.a  
            import os
            import sys
            import threading
            import time
            import _testcapi

            lock = threading.Lock()
            lock.acquire()
            thread_started_event = threading.Event()
            def thread_func():
                try:
                    thread_started_event.set()
                    _testcapi.finalize_thread_hang(lock.acquire)
                finally:
                    # Control must not reach here.
                    os._exit(2)

            t = threading.Thread(target=thread_func)
            t.daemon = True
            t.start()
            thread_started_event.wait()
            # Sleep to ensure daemon thread is blocked on `lock.acquire`
            #
            # Note: This test is designed so that in the unlikely case that
            # `0.1` seconds is not sufficient time for the thread to become
            # blocked on `lock.acquire`, the test will still pass, it just
            # won't be properly testing the thread behavior during
            # finalization.
            time.sleep(0.1)

            def run_during_finalization():
                # Wake up daemon thread
                lock.release()
                # Sleep to give the daemon thread time to crash if it is going
                # to.
                #
                # Note: If due to an exceptionally slow execution this delay is
                # insufficient, the test will still pass but will simply be
                # ineffective as a test.
                time.sleep(0.1)
                # If control reaches here, the test succeeded.
                os._exit(0)

            # Replace sys.stderr.flush as a way to run code during finalization
            orig_flush = sys.stderr.flush
            def do_flush(*args, **kwargs):
                orig_flush(*args, **kwargs)
                if not sys.is_finalizing:
                    return
                sys.stderr.flush = orig_flush
                run_during_finalization()

            sys.stderr.flush = do_flush

            # If the follow exit code is retained, `run_during_finalization`
            # did not run.
            sys.exit(1)
        r?  N)r   r   r@  rH  rI  r
   r5   scripts   & r    test_finalize_daemon_thread_hang,ThreadTests.test_finalize_daemon_thread_hang  sJ    ""$t<< MM<=  :" :v 	v&r    r   z$test needs threading.get_native_id()c                "   R p\        RV4      w  r#pV P                  V^ 4       V P                  VR4       VP                  4       P                  4       pV P                  \	        V4      ^4       V P                  V^ ,          V^,          4       R# )aB  if True:
            import threading
            import os
            from test import support

            parent_thread_native_id = threading.current_thread().native_id
            print(parent_thread_native_id, flush=True)
            assert parent_thread_native_id == threading.get_native_id()
            childpid = os.fork()
            if childpid == 0:
                print(threading.current_thread().native_id, flush=True)
                assert threading.current_thread().native_id == threading.get_native_id()
            else:
                try:
                    assert parent_thread_native_id == threading.current_thread().native_id
                    assert parent_thread_native_id == threading.get_native_id()
                finally:
                    support.wait_process(childpid, exitcode=0)
            r?  r    N)r
   r   rL  r  r   r   )r5   r`  rB  rC  rD  r   s   &     r   test_native_id_after_fork%ThreadTests.test_native_id_after_forkK  s{    & (f5Qc"YY[++-
Z!,JqM:a=9r    rx   Ni  r8  )ArE   rF   rG   rH   maxDiffr   rt   r   r   r   r   r   r   r   r   r   r
  r-  r;  rE  rH  rM  rX  r   
bigmemtestri  rp  r  r  r  r  r   r  r  r  r   
skipUnlessr   r  r  r  r  r  r  r  r  r  r  r	  r  r!  r*  r.  r?  rE  rJ  rN  rQ  rT  r[  ra  r)   rd  rI   rJ   rK   s   @r   rp   rp   x   sE    GD D = =46E/F".H,	 	 2ulUpF#!J<#(0" R%@  A 4%NB&>)" # #> ; ;, Y/1JK3 L 32 Y/1JK% L %N Y/1JK<7 L <7|P5:!#F66$ &* &*P
*4:.8:H"$&2#BO"'AR)<!#F C' C'J O<>de: f :r    rp   c                      a  ] tR tRt o R tR t]R 4       t]R 4       t]	P                  ! ]P                  ]9   R4      ]P                  ! ^(RRR7      R	 4       4       tR
 t]R 4       t]R 4       tRtV tR# )ThreadJoinOnShutdownih  c                    R V,           p\        RV4      w  r#pVP                  4       P                  RR4      pV P                  VR4       R# )a  if 1:
            import sys, os, time, threading

            # a thread, which waits for the main program to terminate
            def joiningfunc(mainthread):
                mainthread.join()
                print('end of thread')
                # stdout is fully buffered because not a tty, we have to flush
                # before exit.
                sys.stdout.flush()
        
r?  r  r   zend of main
end of thread
Nr  )r5   r`  rB  rC  rD  r  s   &&    r   _run_and_join"ThreadJoinOnShutdown._run_and_joinj  sN    
 
 (f5zz|##D"-=>r    c                ,    R pV P                  V4       R# )zif 1:
            import os
            t = threading.Thread(target=joiningfunc,
                                 args=(threading.current_thread(),))
            t.start()
            time.sleep(0.1)
            print('end of main')
            Nrl  r_  s   & r   test_1_join_on_shutdown,ThreadJoinOnShutdown.test_1_join_on_shutdown{  s     	6"r    c                ,    R pV P                  V4       R# )a  if 1:
            from test import support

            childpid = os.fork()
            if childpid != 0:
                # parent process
                support.wait_process(childpid, exitcode=0)
                sys.exit(0)

            # child process
            t = threading.Thread(target=joiningfunc,
                                 args=(threading.current_thread(),))
            t.start()
            print('end of main')
            Nro  r_  s   & r   test_2_join_in_forked_process2ThreadJoinOnShutdown.test_2_join_in_forked_process  s     	6"r    c                ,    R pV P                  V4       R# )a  if 1:
            from test import support

            main_thread = threading.current_thread()
            def worker():
                childpid = os.fork()
                if childpid != 0:
                    # parent process
                    support.wait_process(childpid, exitcode=0)
                    sys.exit(0)

                # child process
                t = threading.Thread(target=joiningfunc,
                                     args=(main_thread,))
                print('end of main')
                t.start()
                t.join() # Should not block: main_thread is already stopped

            w = threading.Thread(target=worker)
            w.start()
            Nro  r_  s   & r   !test_3_join_in_forked_from_thread6ThreadJoinOnShutdown.test_3_join_in_forked_from_thread  s    
* 	6"r    zdue to known OS bugFrZ  c                    \         P                  ! R R7      '       d   V P                  R4       Rp\        RV4      w  r4pV P	                  V4       R# )Tr   r>  a  if True:
            import os
            import random
            import sys
            import time
            import threading

            thread_has_run = set()

            def random_io():
                '''Loop for a while sleeping random tiny amounts and doing some I/O.'''
                import test.test_threading as mod
                while True:
                    with open(mod.__file__, 'rb') as in_f:
                        stuff = in_f.read(200)
                        with open(os.devnull, 'wb') as null_f:
                            null_f.write(stuff)
                            time.sleep(random.random() / 1995)
                    thread_has_run.add(threading.current_thread())

            def main():
                count = 0
                for _ in range(40):
                    new_thread = threading.Thread(target=random_io)
                    new_thread.daemon = True
                    new_thread.start()
                    count += 1
                while len(thread_has_run) < count:
                    time.sleep(0.001)
                # Trigger process shutdown
                sys.exit(0)

            main()
            r?  N)r   r   r@  r
   r   )r5   r[  r`  rB  rC  rD  s   &&    r   test_4_daemon_threads*ThreadJoinOnShutdown.test_4_daemon_threads  sL     ""$// MM9:!D (f5r    c                    R p\        RV4      w  r#pV P                  VR4       V P                  VP                  4       R4       V P                  V^ 4       R# )a  if True:
            import threading
            import time

            def thread2():
                time.sleep(0.05)
                print("OK")

            def thread1():
                time.sleep(0.05)
                t2 = threading.Thread(target=thread2)
                t2.start()

            t = threading.Thread(target=thread1)
            t.start()
            # do not join() -- the interpreter waits for non-daemon threads to
            # finish.
            r?  r    rM  NrK  r5   r`  rB  rC  rD  s   &    r   test_thread_from_thread,ThreadJoinOnShutdown.test_thread_from_thread  sQ    $ (f5c"e,Qr    c                X   R  p\         P                  ! \        RR7      ;_uu_ 4        . p\        ^4       F;  p\        P
                  ! VR7      pVP                  V4       VP                  4        K=  	  V F  pVP                  4        K  	  RRR4       R#   + '       g   i     R# ; i)c                      \         P                  ! 4       p V ^ 8  d   \        P                  ! V ^2R7       R# \         P                  ! ^24       R# )r1   r  N)r  r  r   r  r  )r  s    r   do_fork_and_waitIThreadJoinOnShutdown.test_reinit_tls_after_fork.<locals>.do_fork_and_wait  s/    '')CQw$$S26r    r  r  r   N)	rs   r  r  r   r)   rR   r   r   r   )r5   r  r   r   r   s   &    r   test_reinit_tls_after_fork/ThreadJoinOnShutdown.test_reinit_tls_after_fork  s    
	 $$.@,46 6 G2Y$$,<=q!	 
  6 6 6 6s   A&BB)	c                   . p\        ^4       F<  p\        P                  ! R R7      pVP                  V4       VP	                  4        K>  	   \
        P                  ! \        RR7      ;_uu_ 4        \        P                  ! 4       pV^ 8X  dR   \        \        P                  ! 4       4      ^8X  d   \        P                  ! ^34       M/\        P                  ! ^44       M\        P                  ! V^3R7       RRR4       V F  pVP!                  4        K  	  R#   + '       g   i     L+; i  T F  pTP!                  4        K  	  i ; i)   c                  .    \         P                  ! R 4      # )g333333?r`  rx   r    r   r   KThreadJoinOnShutdown.test_clear_threads_states_after_fork.<locals>.<lambda>   s    Cr    r   r  r  r  N)r   r)   rR   r   r   rs   r  r  r  r  r   r   _current_framesr  r   r  r   )r5   r   r   r   r  s   &    r   $test_clear_threads_states_after_fork9ThreadJoinOnShutdown.test_clear_threads_states_after_fork  s    
 rA  (@AANN1GGI 
	((2D08: :ggi!83..01Q6((r::  : :  s%   $D/ 3BD9D/ D,	'D/ /E
rx   Ni  `)rE   rF   rG   rH   rl  rp  r   rs  rv  r   r"   r   r   r   r   rg  ry  r}  r  r  rI   rJ   rK   s   @r   rj  rj  h  s     ?"
# # #& # #6 __S\\%668MNR%@, A O,\ 0  2  r    rj  c                      a  ] tR tRt o R tR tR t]R 4       t]	R 4       t
RRRR	RR
R/R llt]	R 4       t]	R 4       tRtV tR# )SubinterpThreadingTestsi6  c                   \         P                  ! 4       w  rV P                  \         P                  V4       V P                  \         P                  V4       \	        \         R 4      '       d   \         P
                  ! VR4       W3# )set_blockingF)r  piper'   closer   r  )r5   rws   &  r   r  SubinterpThreadingTests.pipe7  sU    wwy!$!$2~&&OOAu%vr    c                   V P                  4       w  r\        P                  ! R V3,          4      p\        P                  P                  V4      pV P                  V^ 4       V P                  \        P                  ! V^4      R4       R# )a  
            import os
            import random
            import threading
            import time

            def random_sleep():
                seconds = random.random() * 0.010
                time.sleep(seconds)

            def f():
                # Sleep a bit so that the thread is still running when
                # Py_EndInterpreter is called.
                random_sleep()
                os.write(%d, b"x")

            threading.Thread(target=f).start()
            random_sleep()
           xN	r  rH  rI  r   r   run_in_subinterpr   r  readr5   r  r  r  r,  s   &    r   test_threads_join)SubinterpThreadingTests.test_threads_join?  sp     yy{  $ d%  & ll++D1a A-r    c                   V P                  4       w  r\        P                  ! R V3,          4      p\        P                  P                  V4      pV P                  V^ 4       V P                  \        P                  ! V^4      R4       R# )a  
            import os
            import random
            import threading
            import time

            def random_sleep():
                seconds = random.random() * 0.010
                time.sleep(seconds)

            class Sleeper:
                def __del__(self):
                    random_sleep()

            tls = threading.local()

            def f():
                # Sleep a bit so that the thread is still running when
                # Py_EndInterpreter is called.
                random_sleep()
                tls.x = Sleeper()
                os.write(%d, b"x")

            threading.Thread(target=f).start()
            random_sleep()
        r  Nr  r  s   &    r   test_threads_join_2+SubinterpThreadingTests.test_threads_join_2[  sp    
 yy{  2 d3  4 ll++D1a A-r    c                   V P                  4       w  rR pRpRp\        P                  ! 4       pVP                  RV RV: RV RV: RV RV: R24       VP	                  4        V P                  \        P                  ! V^4      V4       V P                  \        P                  ! V^4      V4       V P                  \        P                  ! V^4      V4       R# )	   I   F   Dzif True:
            import os
            import threading
            import time

            done = False

            def notify_fini():
                global done
                done = True
                os.write(z, z)
                t.join()
            threading._register_atexit(notify_fini)

            def task():
                while not done:
                    time.sleep(0.1)
                os.write(z\)
            t = threading.Thread(target=task)
            t.start()

            os.write()
            N)r  r   createexecr  r   r  r  )r5   r_interpw_interpINTERPFINIDONEinterps   &      r   test_threads_join_with_no_main6SubinterpThreadingTests.test_threads_join_with_no_main  s    !YY[$$& 
 #2dX . #2dX . Zr& ,+ 	. 	1-v61-t41-t4r    c                H   \        R 4       R\        P                  P                   R2pRV: R2p\        P                  P	                  4       ;_uu_ 4        \        RV4      w  r4pRRR4       V P                  RXP                  4       4       R#   + '       g   i     L2; i)r  zif 1:
            import os
            import threading
            import time

            def f():
                # Make sure the daemon thread is still running when
                # Py_EndInterpreter is called.
                time.sleep(zJ)
            threading.Thread(target=f, daemon=True).start()
            zKif 1:
            import _testcapi

            _testcapi.run_in_subinterp(r  r?  Nz:Fatal Python error: Py_EndInterpreter: not the last thread)r	   r   r   r(  SuppressCrashReportr   r   r  )r5   subinterp_coder`  rB  rC  rD  s   &     r   test_daemon_threads_fatal_error7SubinterpThreadingTests.test_daemon_threads_fatal_error  s    k" !LL667 8
 "	$
 \\--//0v>LBS 0 ,-0ZZ\	; 0/s   BB!	allowedTdaemon_allowedr'  Fc                  \        R 4       \        P                  ! RV RV R24      p\        \        P
                  4      p\        P                  ! RV: RV RV RV R2	4      p\        P                  P                  4       ;_uu_ 4        \        R	V4      w   rR
R
R
4       V	P                  4       #   + '       g   i     X	P                  4       # ; i)_testinternalcapiz
            import test.support
            import threading
            def func():
                print('this should not have run!')
            t = threading.Thread(target=func, daemon=r  z#
            t.start()
            zh
            import test.support
            test.support.run_in_subinterp_with_config(
                z,
                use_main_obmalloc=True,
                allow_fork=True,
                allow_exec=True,
                allow_threads=z',
                allow_daemon_threads=z0,
                check_multi_interp_extensions=z;,
                own_gil=False,
            )
            r?  N)
r	   rH  rI  boolr   Py_GIL_DISABLEDr   r  r
   r  )
r5   before_startr  r  r'  r  check_multi_interp_extensionsr`  r  rD  s
   &&$$$     r   _check_allowed&SubinterpThreadingTests._check_allowed  s    
 	)*! .6
 7=X >N *  )-W-D-D(E% &  " #  'i (&&4%5 6//L.M N"  \\--//(v6IAq 0zz| 0/zz|s   B44C	c                R    V P                  R R R R7      pV P                  RV4       R# )Fr  r  r'  r  N)r  r   r5   rD  s   & r   test_threads_not_allowed0SubinterpThreadingTests.test_threads_not_allowed  s0    !!  " 

 	nc*r    c           	     v   V P                  R 4      ;_uu_ 4        V P                  RRRR7      pV P                  RV4       RRR4       V P                  R4      ;_uu_ 4        V P                  RRRRR7      pV P                  RV4       RRR4       R#   + '       g   i     L[; i  + '       g   i     R# ; i)zvia Thread()TFr  r  Nzvia Thread.daemon setterzt.daemon = True)r   r  r   r  s   & r   test_daemon_threads_not_allowed7SubinterpThreadingTests.test_daemon_threads_not_allowed  s    \\.))%%$ & C
 MM.#. * \\455%%!$	 & C MM.#. 65 *) 655s   'B"(B'B$	'B8	rx   N)r   )rE   rF   rG   rH   r  r  r  r$   r  r   r  r  r  r  rI   rJ   rK   s   @r   r  r  6  s     .8#.J #5 #5J ; ;.#&* $B + + / /r    r  c                      a  ] tR tRt o R tR tR tR tR t]	! 4       R 4       t
R tR	 tR
 tR tR tR tR tRtV tR# )ThreadingExceptionTestsi  c                    \         P                  ! 4       pVP                  4        V P                  \        VP                  4       VP                  4        R # rB   )r)   rR   r   r   r  r   r5   r   s   & r   test_start_thread_again/ThreadingExceptionTests.test_start_thread_again  s6    !!#,5r    c                p    \         P                  ! 4       pV P                  \        VP                  4       R # rB   )r)   r   r   r  r   )r5   r   s   & r   test_joining_current_thread3ThreadingExceptionTests.test_joining_current_thread  s&    "113,(;(;<r    c                p    \         P                  ! 4       pV P                  \        VP                  4       R # rB   )r)   rR   r   r  r   r  s   & r   test_joining_inactive_thread4ThreadingExceptionTests.test_joining_inactive_thread	  s$    !!#,4r    c                    \         P                  ! 4       pVP                  4        V P                  \        \
        VR R4       VP                  4        R# r  )r)   rR   r   r   r  r(   r   r  s   & r   test_daemonize_active_thread4ThreadingExceptionTests.test_daemonize_active_thread  s8    !!#,4Hr    c                p    \         P                  ! 4       pV P                  \        VP                  4       R # rB   )r)   r   r   r  r   )r5   rm  s   & r   test_releasing_unacquired_lock6ThreadingExceptionTests.test_releasing_unacquired_lock  s"    ~~,5r    c                   R pRp\         P                  ! \        P                  RV.\         P                  \         P                  R7      pVP                  4       w  rEVP                  4       P                  RR4      pV P                  VP                  ^ RVP                  4       ,           4       V P                  Wb4       R# )a  if True:
            import threading

            def recurse():
                return recurse()

            def outer():
                try:
                    recurse()
                except RecursionError:
                    pass

            w = threading.Thread(target=outer)
            w.start()
            w.join()
            print('end of main thread')
            zend of main thread
r?  )stdoutstderrr  r   zUnexpected error: N)

subprocessPopenr   
executablePIPEcommunicater  r  r   
returncode)r5   r`  expected_outputpr  r  r  s   &      r   test_recursion_limit,ThreadingExceptionTests.test_recursion_limit  s    " 1cnndF;$.OOJOOM}}&&tR0q*>*PQ/r    c                    R p\        RV4      w  r#pV P                  VR4       VP                  4       pV P                  RV4       V P                  RV4       V P                  RV4       V P	                  RV4       R# )a  if True:
            import threading
            import time

            running = False
            def run():
                global running
                running = True
                while running:
                    time.sleep(0.01)
                1/0
            t = threading.Thread(target=run)
            t.start()
            while not running:
                time.sleep(0.01)
            running = False
            t.join()
            r?  r    Exception in thread"Traceback (most recent call last):ZeroDivisionErrorUnhandled exceptionNr
   r   r  r   r   r|  s   &    r   test_print_exception,ThreadingExceptionTests.test_print_exception7  st    $ (f5c"jjl+S1:C@)3/.4r    c                    R p\        RV4      w  r#pV P                  VR4       VP                  4       pV P                  RV4       V P                  RV4       V P                  RV4       V P	                  RV4       R# )a  if True:
            import sys
            import threading
            import time

            running = False
            def run():
                global running
                running = True
                while running:
                    time.sleep(0.01)
                1/0
            t = threading.Thread(target=run)
            t.start()
            while not running:
                time.sleep(0.01)
            sys.stderr = None
            running = False
            t.join()
            r?  r    r  r  r  r  Nr  r|  s   &    r   %test_print_exception_stderr_is_none_1=ThreadingExceptionTests.test_print_exception_stderr_is_none_1R  st    ( (f5c"jjl+S1:C@)3/.4r    c                    R p\        RV4      w  r#pV P                  VR4       V P                  RVP                  4       4       R# )a  if True:
            import sys
            import threading
            import time

            running = False
            def run():
                global running
                running = True
                while running:
                    time.sleep(0.01)
                1/0
            sys.stderr = None
            t = threading.Thread(target=run)
            t.start()
            while not running:
                time.sleep(0.01)
            running = False
            t.join()
            r?  r    r  N)r
   r   r   r  r|  s   &    r   %test_print_exception_stderr_is_none_2=ThreadingExceptionTests.test_print_exception_stderr_is_none_2o  sB    ( (f5c".

=r    c                "    R p\        RV4       R# )a9  if True:
            import time
            import threading
            import _thread

            def f():
                try:
                    f()
                except RecursionError:
                    f()

            def g():
                try:
                    raise ValueError()
                except* ValueError:
                    f()

            def h():
                time.sleep(1)
                _thread.interrupt_main()

            t = threading.Thread(target=h)
            t.start()
            g()
            t.join()
            r?  N)r   r_  s   & r   test_print_exception_gh_1020566ThreadingExceptionTests.test_print_exception_gh_102056  s    6 	dF+r    c                  a R  o ! V3R lR\         P                  4      pV! 4       pVP                  4        VP                  4        V P	                  VP
                  4       V P                  VP
                  \        4       RVn        R# )c                      h rB   rx   rx   r    r   
bare_raiseOThreadingExceptionTests.test_bare_raise_in_brand_new_thread.<locals>.bare_raise  s    r    c                   2   <a  ] tR tRt o RtV3R ltRtV tR# )OThreadingExceptionTests.test_bare_raise_in_brand_new_thread.<locals>.Issue27558i  Nc                V   <  S! 4        R #   \          d   pYn         R p?R # R p?ii ; irB   )r#  exc)r5   r  r  s   & r   ra   SThreadingExceptionTests.test_bare_raise_in_brand_new_thread.<locals>.Issue27558.run  s$    #L  #"HH#s    (#()r  )rE   rF   rG   rH   r  ra   rI   rJ   )rL   r  s   @r   
Issue27558r    s     C# #r    r  N)r)   rR   r   r   r   r  r   r  )r5   r  r   r  s   &  @r   #test_bare_raise_in_brand_new_thread;ThreadingExceptionTests.test_bare_raise_in_brand_new_thread  sb    		#)) 	# VZZ(fjj,7
r    c                "   R  pV P                  \        P                  \        P                  4       \	        ^d4       Uu. uF  p\
        P                  ! VR7      NK  	  ppV F#  pVP                  4        VP                  4        K%  	  R# u upi )c                      \        \        P                  R RR7      ;_uu_ 4       p V P                  R4       \        P
                  ! 4        RRR4       R#   + '       g   i     R# ; i)r  r  )encoding N)openr   TESTFNwrite	tracebackformat_stack)fps    r   modify_fileQThreadingExceptionTests.test_multithread_modify_file_noerror.<locals>.modify_file  s?    i&&g>>"&&( ?>>>s   'AA'	r   N)	r'   r   unlinkr  r   r)   rR   r   r   )r5   r  r   r   r   s   &    r   $test_multithread_modify_file_noerror<ThreadingExceptionTests.test_multithread_modify_file_noerror  sw    	)
 		(()*:*:; 3Z
 K0 	 
 AGGIFFH 	
s    Bc                    R p\        RV4      w  r#pV P                  V^ 4       V P                  VR4       V P                  VR4       R# )zif True:
        import sys
        import threading

        threading.x = sys.modules[__name__]
        x = threading._DummyThread()
        r?  r    Nr  r  s   &    r   )test_dummy_thread_on_interpreter_shutdownAThreadingExceptionTests.test_dummy_thread_on_interpreter_shutdown  sK    
 (d3Qc"c"r    rx   N)rE   rF   rG   rH   r  r  r  r  r  r   r  r  r  r  r  r   r  r  rI   rJ   rK   s   @r   r  r    s]     >56 0 0>565:>2,>* # #r    r  c                   &   a  ] tR tRt o R tRtV tR# )ThreadRunFaili  c                    \        R 4      h)
run failedr  r4   s   &r   ra   ThreadRunFail.run  s    &&r    rx   Nr  rK   s   @r   r  r    s     ' 'r    r  c                      a a ] tR tRt oV 3R lt]R 4       t]P                  ]R 4       4       t	R t
R tR tR tR	tVtV ;t# )
ExceptHookTestsi  c                :   < \        V 4       \        SV `	  4        R # rB   )r,   superrh   )r5   	__class__s   &r   rh   ExceptHookTests.setUp  s    "4(r    c                   \         P                  ! R 4      ;_uu_ 4       p\        RR7      pVP                  4        VP	                  4        RRR4       XP                  4       P                  4       pV P                  RXP                   R2V4       V P                  RV4       V P                  RV4       V P                  RV4       R#   + '       g   i     L; i)	r  excepthook threadrP   NException in thread :
#Traceback (most recent call last):
z   raise ValueError("run failed")zValueError: run failed)	r   captured_outputr  r   r   getvaluerL  r   rQ   )r5   r  r   s   &  r   test_excepthookExceptHookTests.test_excepthook  s    $$X..&"(;<FLLNKKM /
 "((*,V[[M=vF<fE8&A.7 /.s   -C

C	c                Z   \         P                  ! R 4      ;_uu_ 4       p \        R4      h  \         dX   p\        P
                  ! . \        P                  ! 4       ORN4      p \        P                  ! T4       Rp Rp?M  Rpi ; iRp?ii ; i RRR4       M  + '       g   i     M; iXP                  4       P                  4       pT P                  R\        P                  ! 4        R2T4       T P                  RT4       T P                  RT4       T P                  RT4       R# )r  bugNr"  r#  r$  z  raise ValueError("bug")zValueError: bug)r   r%  r  r#  r)   ExceptHookArgsr   exc_infor&   r&  rL  r   r  )r5   r  r  r   s   &   r   test_excepthook_thread_None+ExceptHookTests.test_excepthook_thread_None  s    
 $$X..&  ''   //0G#,,.0G$0GH ((.  D4D   /... "((*,Y-@-@-B,C3GP<fE16:'0sC   B,B-B	%B;B	=BB	B		BBB+	c                :    ! R  R\         P                  4      p\        P                  ! R4      ;_uu_ 4       pV! 4       pVP	                  4        VP                  4        RRR4       V P                  XP                  4       R4       R#   + '       g   i     L2; i)c                   &   a  ] tR tRt o R tRtV tR# )4ExceptHookTests.test_system_exit.<locals>.ThreadExiti  c                2    \         P                  ! ^4       R# r9   )r   exitr4   s   &r   ra   8ExceptHookTests.test_system_exit.<locals>.ThreadExit.run  s    r    rx   Nr  rK   s   @r   
ThreadExitr1    s      r    r5  r  Nr   )r)   rR   r   r%  r   r   r   r&  )r5   r5  r  r   s   &   r   test_system_exit ExceptHookTests.test_system_exit  si    	)) 	
 $$X..&\FLLNKKM /
 	*B/ /.s   (B

B	c                "  a R oV3R lp \         P                  ! \        RV4      ;_uu_ 4        \        4       pVP	                  4        VP                  4        R R R 4       V P                  SP                  \        4       V P                  \        SP                  4      R4       V P                  SP                  SP                  P                  4       V P                  SP                  X4       R oR #   + '       g   i     L; i  R oi ; i)Nc                    < V oR # rB   rx   )	hook_argsr   s   &r   hook4ExceptHookTests.test_custom_excepthook.<locals>.hook  s    Dr    r&   r  )r   	swap_attrr)   r  r   r   r   exc_typer  r   	exc_valueexc_traceback__traceback__r   r   )r5   r;  r   r   s   &  @r   test_custom_excepthook&ExceptHookTests.test_custom_excepthook  s    		""9lDAA& B
 T]]J7S0,?T//1M1MNMM$++v. D BA Ds#   $D
 +C7BD
 7D	D
 
Dc                J  a R  pRoV3R lp\         P                  ! \        RV4      ;_uu_ 4        \         P                  ! \        RV4      ;_uu_ 4        \         P                  ! R4      ;_uu_ 4       p\        4       pVP                  4        VP                  4        RRR4       RRR4       RRR4       V P                  XP                  4       R4       V P                  SR4       R#   + '       g   i     LT; i  + '       g   i     L_; i  + '       g   i     Lj; i)c                     \        R 4      h)threading_hook failedr  r  s   &r   threading_hookCExceptHookTests.test_custom_excepthook_fail.<locals>.threading_hook.  s    455r    Nc                    < \        V4      oR # rB   r   )r>  r?  r@  err_strs   &&&r   sys_hook=ExceptHookTests.test_custom_excepthook_fail.<locals>.sys_hook3  s    )nGr    r&   r  z#Exception in threading.excepthook:
rF  )
r   r=  r)   r   r%  r  r   r   r   r&  )r5   rG  rK  r  r   rJ  s   &    @r   test_custom_excepthook_fail+ExceptHookTests.test_custom_excepthook_fail-  s    	6 	% y,GGsL(;;$$X..&"_FLLNKKM / < H 	*?	A"9: /. <; HGs;   %DC?	5+C, C?	(D,C<7C?	?D
DD"	c                Z   R  pR pV! 4       p\         P                  ! \        RV4      ;_uu_ 4        V! 4       p\        P                  \        n        V! 4       pRRR4       V P                  VX4       V P                  VX4       V P                  VR4       R#   + '       g   i     LH; i)c                     \         P                  ! R 4      ;_uu_ 4       p \        RR7      pVP                  4        VP	                  4        RRR4       V P                  4       #   + '       g   i     X P                  4       # ; i)r  r!  rP   N)r   r%  r  r   r   r&  )outputr   s     r   
run_thread<ExceptHookTests.test_original_excepthook.<locals>.run_threadC  s^    ((22f&,?@ 3 ??$$	 32 ??$$s   -A$$B	c                 <    \        R \        P                  R7       R# )zRunning a thread failed)fileN)r[   r   r  r  s   &r   rG  @ExceptHookTests.test_original_excepthook.<locals>.threading_hookJ  s    +#**=r    r&   NzRunning a thread failed
)r   r=  r)   r*   r&   r   r   )r5   rR  rG  default_outputcustom_hook_outputrecovered_outputs   &     r   test_original_excepthook(ExceptHookTests.test_original_excepthookB  s    	%	> $y,GG!+#,#;#;I )| H
 	)9:N,>?+-HI HGs   (BB*	rx   )rE   rF   rG   rH   rh   r   r'  r   r   r-  r6  rB  rM  rZ  rI   rJ   __classcell__r  rL   s   @@r   r  r    s[      
8 
8 1  1(0*;*J Jr    r  c                   2   a  ] tR tRt o R tR tR tRtV tR# )
TimerTestsiX  c                r    \         P                  V 4       . V n        \        P                  ! 4       V n        R # rB   )rd   rh   callback_argsr)   r   callback_eventr4   s   &r   rh   TimerTests.setUpZ  s'    4 'oo/r    c                   \         P                  ! R V P                  4      pVP                  4        V P                  P                  4        VP                  P                  R4       RVP                  R&   V P                  P                  4        \         P                  ! R V P                  4      pVP                  4        V P                  P                  4        V P                  \        V P                  4      ^4       V P                  V P                  R/ 3R/ 3.4       VP                  4        VP                  4        R# )rg  blahbarfooNrx   )r)   Timer_callback_spyr   rb  r   r   r   r3  r  r   r   ra  r   )r5   timer1timer2s   &  r    test_init_immutable_default_args+TimerTests.test_init_immutable_default_args_  s     t'9'9:  "6"$e!!#t'9'9:  "T//0!4++r2hR-ABr    c                    V P                   P                  VR ,          VP                  4       34       V P                  P	                  4        R# ):NNNN)ra  r   copyrb  r   )r5   r   r3  s   &*,r   ri  TimerTests._callback_spyp  s7    !!47FKKM":;!r    )ra  rb  N)	rE   rF   rG   rH   rh   rl  ri  rI   rJ   rK   s   @r   r_  r_  X  s     0
"" "r    r_  c                   :    ] tR tRt]! ]P                  4      tRtR# )	LockTestsit  rx   N)	rE   rF   rG   rH   staticmethodr)   r   locktyperI   rx   r    r   rr  rr  t  s    INN+Hr    rr  c                   :    ] tR tRt]! ]P                  4      tRtR# )PyRLockTestsiw  rx   N)	rE   rF   rG   rH   rs  r)   _PyRLockrt  rI   rx   r    r   rv  rv  w  s    I../Hr    rv  zRLock not implemented in Cc                   J   a  ] tR tRt o ]! ]P                  4      tR tRt	V t
R# )CRLockTestsiz  c           
        \         P                  ! R R7      ;_uu_ 4       p\        P                  ! 4        RRR4       V P	                  X. 4       R/ 3R	R^/3R
R^/3.pV Fd  w  r4V P                  W4R7      ;_uu_ 4        V P                  \        4      ;_uu_ 4        \        P                  ! V/ VB  RRR4       RRR4       Kf  	   ! R RV P                  4      p\         P                  ! R R7      ;_uu_ 4       pV! ^^R7       RRR4       V P	                  V. 4       R#   + '       g   i     L; i  + '       g   i     L; i  + '       g   i     K  ; i  + '       g   i     L^; i)T)recordNr   r2  c                   >   a a ] tR tRt oV3R lV 3R lltRtVtV ;t# )/CRLockTests.test_signature.<locals>.CustomRLocki  c                   < V ^8  d   QhRR/# )   returnNrx   )formatrL   s   "r   __annotate__<CRLockTests.test_signature.<locals>.CustomRLock.__annotate__  s     # #4 #r    c               $   < \         SV `  4        R # rB   )r  r6   )r5   r   r   r  s   &&$r   r6   8CRLockTests.test_signature.<locals>.CustomRLock.__init__  s     "r    rx   )rE   rF   rG   rH   r6   rI   rJ   r\  r]  s   @@r   CustomRLockr}    s     # # #r    r  )r   r   rx   )r:   r  )	rs   r  r)   r   r   r   assertWarnsr  rt  )r5   warnings_log	arg_typesr   r3  r  s   &     r   test_signatureCRLockTests.test_signature~  s   $$D11\OO 2r* 2J#qNc1X
	
 &LD477%%&899OOT4V4 : 87 &	#$-- 	# $$D11\Q 2r*+ 21 :9 877 21s;   D$ E
D75E
=E$D4	7EE

EE.	rx   N)rE   rF   rG   rH   rs  r)   _CRLockrt  r  rI   rJ   rK   s   @r   ry  ry  z  s     I--.H+ +r    ry  c                   :    ] tR tRt]! ]P                  4      tRtR# )
EventTestsi  rx   N)	rE   rF   rG   rH   rs  r)   r   	eventtyperI   rx   r    r   r  r    s    Y__-Ir    r  c                   J   a  ] tR tRt o ]! ]P                  4      tR tRt	V t
R# )ConditionAsRLockTestsi  c                (    V P                  R 4       R# )z,Condition does not expose _recursion_count()N)r@  r4   s   &r   test_recursion_count*ConditionAsRLockTests.test_recursion_count  s    DEr    rx   N)rE   rF   rG   rH   rs  r)   r  rt  r  rI   rJ   rK   s   @r   r  r    s!     I//0HF Fr    r  c                   :    ] tR tRt]! ]P                  4      tRtR# )ConditionTestsi  rx   N)	rE   rF   rG   rH   rs  r)   r  condtyperI   rx   r    r   r  r    s    I//0Hr    r  c                   :    ] tR tRt]! ]P                  4      tRtR# )SemaphoreTestsi  rx   N)	rE   rF   rG   rH   rs  r)   	SemaphoresemtyperI   rx   r    r   r  r    s    9../Gr    r  c                   :    ] tR tRt]! ]P                  4      tRtR# )BoundedSemaphoreTestsi  rx   N)	rE   rF   rG   rH   rs  r)   r   r  rI   rx   r    r   r  r    s    9556Gr    r  c                   :    ] tR tRt]! ]P                  4      tRtR# )BarrierTestsi  rx   N)	rE   rF   rG   rH   rs  r)   BarrierbarriertyperI   rx   r    r   r  r    s    y001Kr    r  c                     a  ] tR tRt o R t]P                  ! ]! ]R4      R4      ]P                  ! ]! ]R4      R4      R 4       4       t	]P                  ! ]! ]R4      R4      ]P                  ! ]! ]R4      R4      R 4       4       t
R	tV tR
# )MiscTestCasei  c                f    \        V 4       R 0pRR0p\        P                  ! V \        RWR7       R# )r1  r  r  )extranot_exportedN)r)   r   )r,   r   check__all__r)   )r5   r  r  s   &  r   test__all__MiscTestCase.test__all__  s4    "4('7T9.F#(	Er    set_namezmissing _thread.set_name	_get_namezmissing _thread._get_namec                \  a \        \        R R4      pT;'       g    ^dpRRRRV,          RV^
,           ,          RV^,
          ,          R,           RV^,
          ,          R,           RV^,
          ,          R,           RRV,          ,           R	RV,          ,           R
RV,          ,           RRV,          ,           .p\        P                  '       d#   VP	                  R\        P                   24       \        P
                  '       d    VP	                  \        P
                  4       \        P                  P                  R4      '       d   RpM\        P                  ! 4       pV3R lpV EF  p\        P                  '       g   VP                  VR4      pRV9   d   VP                  R^4      ^ ,          pVe   VRV p\        P                  P                  R4      '       d   VP                  RR4      pM\        P                   ! V4      pMz^ p	. p
V F?  p\#        V4      R8  d   V	^,          p	M	V	^,          p	W8  d    MV
P	                  V4       KA  	  RP%                  V
4      pRV9   d   VP                  R^4      ^ ,          pV P'                  WhR7      ;_uu_ 4        Ro\(        P*                  ! WVR7      pVP-                  4        VP%                  4        V P/                  SVR\1        S4      : R\1        V4      : 24       RRR4       EK  	  R#   + '       g   i     EK  ; i)_NAME_MAXLENN
CustomNameu   namé€z
embed nullxu   é€u   􏿿u   🐍xxxxxxxxxz	nonascii:sunosr  c                  2   < \         P                  ! 4       o R # rB   )r   r  )	work_names   r   work(MiscTestCase.test_set_name.<locals>.work  s    ))+Ir    r      surrogateescapei  r    )rQ   expectedr   zlen(work_name)=z and len(expected)=u   􏿿􏿿)getattrr   r   FS_NONASCIIr   TESTFN_UNENCODABLEr   r   
startswithgetfilesystemencodingr   
MS_WINDOWSencodesplitr  r  fsdecodeordr   r   r)   rR   r   r   r   )r5   truncater  testsr  r  rQ   encodedr  r[  charschr   r  s   &            @r   test_set_nameMiscTestCase.test_set_name  s    7ND9C    %K 52: 519' 519,519 00,&&<%''L5((\E))7
:    LL9Y%:%:$;<='''LL556<<""7++H002H	, D%%%++h	:G#%mmE15a8G'%ix0G<<**733&~~g7HIH!{{73HB2w'		LL$  775>8#'~~dA6q9H4;; 	"))A  H$3C	N#44H#h-9I!JL <;7 6 <;;s   #A'LL+c                   aa R oR oVV3R lp\         P                  ! VRR7      pVP                  4        VP                  4        V P	                  SR4       V P	                  SR4       R # )Nc                     < \         P                  ! 4       o R \        P                  ! 4       n        \         P                  ! 4       oR# )new nameN)r   r  r)   r   rQ   )name1name2s   r   r  +MiscTestCase.test_change_name.<locals>.work	  s0    %%'E.8I$$&+%%'Er    rQ   r   r  )r)   rR   r   r   r   )r5   r  r   r  r  s   &  @@r   test_change_nameMiscTestCase.test_change_name	  sZ    
 	( !!F;'
+r    rx   N)rE   rF   rG   rH   r  r   rh  r   r   r  r  rI   rJ   rK   s   @r   r  r    s     E *57QR+68STQL U SQLf *57QR+68ST, U S,r    r  c                      a  ] tR tRt o R tR t]! R4      R 4       tR tR t	R t
R	 t]P                  R
 4       tRtV tR# )InterruptMainTestsi	  c                   R  p\         P                   ! W4      pV P                  \         P                   W4       V P                  \        4      ;_uu_ 4        \        P
                  ! 4        RRR4       R#   + '       g   i     R# ; i)c                     ^^ ,           R# r9   rx   )signumr  s   &&r   handlerLInterruptMainTests.check_interrupt_main_with_signal_handler.<locals>.handler!	  s    aCCr    N)signalr'   r   r  r   interrupt_main)r5   r  r  old_handlers   &&  r   (check_interrupt_main_with_signal_handler;InterruptMainTests.check_interrupt_main_with_signal_handler 	  sV    	 mmF4v;011""$ 2111s   A77B	c                   \         P                  ! V4      p \         P                   ! V\         P                  4       \        P                  ! V4       \         P                   ! V\         P
                  4       \        P                  ! V4       \         P                   ! W4       R #   \         P                   ! Y4       i ; irB   )r  	getsignalSIG_IGNr   r  SIG_DFL)r5   r  r  s   && r   check_interrupt_main_noerror/InterruptMainTests.check_interrupt_main_noerror*	  sr    ""6*		+MM&&..1""6*MM&&..1""6* MM&*FMM&*s   A6B& &B>z*gh-118433: Flaky due to a longstanding bugc                   R  p\         P                  ! VR7      pV P                  \        4      ;_uu_ 4        VP	                  4        VP                  4        RRR4       VP                  4        R#   + '       g   i     L"; i)c                  0    \         P                  ! 4        R # rB   )r   r  rx   r    r   call_interruptHInterruptMainTests.test_interrupt_main_subthread.<locals>.call_interrupt;	  s    ""$r    r   N)r)   rR   r   KeyboardInterruptr   r   )r5   r  r   s   &  r   test_interrupt_main_subthread0InterruptMainTests.test_interrupt_main_subthread7	  sT    	%N3011GGIFFH 2 	
 21s   !A33B	c                    V P                  \        4      ;_uu_ 4        \        P                  ! 4        R R R 4       R #   + '       g   i     R # ; irB   )r   r  r   r  r4   s   &r   test_interrupt_main_mainthread1InterruptMainTests.test_interrupt_main_mainthreadC	  s1     011""$ 2111s	   >A	c                    V P                  \        P                  4       V P                  \        P                  4       R # rB   )r  r  SIGINTSIGTERMr4   s   &r   'test_interrupt_main_with_signal_handler:InterruptMainTests.test_interrupt_main_with_signal_handlerI	  s&    55fmmD55fnnEr    c                    V P                  \        P                  4       V P                  \        P                  4       R # rB   )r  r  r  r  r4   s   &r   test_interrupt_main_noerror.InterruptMainTests.test_interrupt_main_noerrorM	  s&    ))&--8))&..9r    c                    V P                  \        \        P                  R4       V P                  \        \        P                  \        P
                  4       V P                  \        \        P                  R4       R# )r:   i@B Nr  )r   r  r   r  r  NSIGr4   s   &r   "test_interrupt_main_invalid_signal5InterruptMainTests.test_interrupt_main_invalid_signalQ	  sN    *g&<&<bA*g&<&<fkkJ*g&<&<gFr    c                    R .pR.pR.pR p\         P                  ! WBW3R7      pVP                  4        V^ ,          '       g   K  RV^ &   VP                  4        V P	                  V^ ,          4       R# )TFc                 h    R pRV ^ &   V^ ,          '       d   V'       d   V^,          pMR# K%  RV^ &   R# )i TNrx   )r  continterrupted
iterationss   &&& r   ra  AInterruptMainTests.test_can_interrupt_tight_loops.<locals>.worker\	  s4    $JGAJq''!OJ!KNr    r   N)r)   rR   r   r   r   )r5   r  r  r   ra  r   s   &     r   test_can_interrupt_tight_loops1InterruptMainTests.test_can_interrupt_tight_loopsV	  sj    v'g		" F$0LM		!**Q	A'r    rx   N)rE   rF   rG   rH   r  r  r   r  r  r  r  r  r   reap_threadsr  rI   rJ   rK   s   @r   r  r  	  sZ     %+ FG	 H	%F:G
 ""( #(r    r  c                   2   a  ] tR tRt o R tR tR tRtV tR# )AtexitTestsip	  c                    \        R R4      w  rpV P                  V4       V P                  VP                  4       R4       R# )r?  zif True:
            import threading

            def run_last():
                print('parrot')

            threading._register_atexit(run_last)
        s   parrotN)r
   r   r   rL  rA  s   &   r   test_atexit_outputAtexitTests.test_atexit_outputr	  s=    ' /  	i0r    c                F    \        R R4      w  rpV P                  V4       R# )r?  aN  if True:
            import threading
            from unittest.mock import Mock

            mock = Mock()
            threading._register_atexit(mock)
            mock.assert_not_called()
            # force early shutdown to ensure it was called once
            threading._shutdown()
            mock.assert_called_once()
        N)r
   r   rA  s   &   r   test_atexit_called_once#AtexitTests.test_atexit_called_once	  s'    ' 
/ 
 	r    c                    \        R R4      w  rpV P                  V4       V P                  RVP                  4       4       R# )r?  zif True:
            import threading

            def func():
                pass

            def run_last():
                threading._register_atexit(func)

            threading._register_atexit(run_last)
        z2RuntimeError: can't register atexit after shutdownN)r
   r   r   r  rA  s   &   r   test_atexit_after_shutdown&AtexitTests.test_atexit_after_shutdown	  s?     ( 
/ 
 	J

	r    rx   N)	rE   rF   rG   rH   r	  r  r  rI   rJ   rK   s   @r   r  r  p	  s     1 r    r  __main__)netbsd5zhp-ux11)F__doc__test.supportr   r   r   r   r   r   r   test.support.import_helperr   r	   test.support.script_helperr
   r   r   rZ   r   r   r)   r]   r   r  r  r  r  rH  r	  rs   r   r   r   
concurrentr   rZ  requires_working_threadingr   r   r$   r,   r   r.   rR   rN   TestCaserd   rp   rj  r  r  r  r  r_  rr  
RLockTestsrv  r"   r  ry  r  r  r  r  r  r  r  r  r  rE   r  rx   r    r   <module>r     sW    T T 9 9 I N ,  
      	        '  + +4 8 + 	=4f <!! <B%8$$ %n:, n:`'K< K\C/l C/L_#l _#D'I$$ '
rJl rJj" "8,
$$ ,0:(( 0 
""d*,HI+*'' + J+6.&& .FJ11 F1Z.. 10Z.. 07J<< 72:** 2o,8$$ o,dN(** N(b/(## /d zMMO EL  Ls   8I" "	I/.I/