
    0hh=                       S r SSKrSSKJrJrJr  SSKJrJrJr  SSK	J
r
  SSKJrJr  SSKJr  SSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKJr  SS	KJr  SS
KJr   SSKJr  \RB                  " SS9  Sr"S r#S r$S r% " S S\&5      r' " S S\RP                  5      r) " S S\RT                  5      r+ " S S\+5      r, " S S\+5      r- " S S\+5      r. " S S\+5      r/ " S  S!\RP                  5      r0 " S" S#\+5      r1 " S$ S%\+5      r2 " S& S'\Rf                  5      r3 " S( S)\Rh                  5      r5\Rl                  " \Rn                  SL S*5       " S+ S,\Rh                  5      5       r8 " S- S.\Rr                  5      r9 " S/ S0\Rh                  5      r: " S1 S2\Rv                  5      r; " S3 S4\Rx                  5      r< " S5 S6\Rz                  5      r= " S7 S8\R|                  5      r> " S9 S:\RT                  5      r? " S; S<\RT                  5      r@ " S= S>\RT                  5      rA\BS?:X  a  \R                  " 5         gg! \  a    Sr GNf = f)@z!
Tests for the threading module.
    N)threading_helperrequires_subprocessrequires_gil_enabled)verbosecpython_only	os_helper)import_module)assert_python_okassert_python_failure)force_not_colorized)mock)
lock_tests)support)interpretersT)module)netbsd5zhp-ux11c                    [         R                  (       d  [        R                  " S5      " U 5      $ [        R
                  [        ;   a  [        R                  " S5      " U 5      $ [         R                  (       a  [        R                  " S5      " U 5      $ [         R                  " SS9(       a  [        R                  " S5      " U 5      $ U $ )Nz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    </opt/python-3.13.8/usr/lib/python3.13/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    [         R                  " [        SL S5      " U 5      $ )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                     U R                  [        [        S[        R                  5        [        R                  [        l        g )N
excepthook)
addCleanupsetattr	threadingr'   __excepthook__)testcases    r   restore_default_excepthookr-   >   s*    L):N:NO$33Ir!   c                   ,    \ rS rSrS rS rS rS rSrg)CounterD   c                     SU l         g Nr   valueselfs    r   __init__Counter.__init__E   s	    
r!   c                 .    U =R                   S-  sl         g N   r3   r5   s    r   incCounter.incG       

a
r!   c                 .    U =R                   S-  sl         g r:   r3   r5   s    r   decCounter.decI   r>   r!   c                     U R                   $ Nr3   r5   s    r   getCounter.getK   s    zzr!   r3   N)	__name__
__module____qualname____firstlineno__r7   r<   r@   rD   __static_attributes__ r!   r   r/   r/   D   s    r!   r/   c                        \ rS rSrS rS rSrg)
TestThreadN   c                 n    [         R                  R                  XS9  X l        X0l        X@l        XPl        g )Nname)r*   Threadr7   r,   semamutexnrunning)r6   rQ   r,   rS   rT   rU   s         r   r7   TestThread.__init__O   s-    !!$!2 	
 r!   c                    [         R                   " 5       S-  n[        (       a  [        SU R                  US-  4-  5        U R                     U R
                     U R                  R                  5         [        (       a$  [        U R                  R                  5       S5        U R                  R                  U R                  R                  5       S5        S S S 5        [        R                  " U5        [        (       a  [        SU R                  S5        U R
                     U R                  R                  5         U R                  R                  U R                  R                  5       S5        [        (       a2  [        S	U R                  U R                  R                  5       4-  5        S S S 5        S S S 5        g ! , (       d  f       N= f! , (       d  f       N(= f! , (       d  f       g = f)
Ng     @ztask %s will run for %.1f usecg    .Aztasks are running   taskdoner   z$%s is finished. %d tasks are running)randomr   printrQ   rS   rT   rU   r<   rD   r,   assertLessEqualtimesleepr@   assertGreaterEqual)r6   delays     r   runTestThread.runV   sE   ')7299eck*+ , YY!!#7$--++-/BC--dmm.?.?.A1E	  JJuwfdii0!!#001B1B1DaH7@99dmm&7&7&9:; <	  Y  Ys?   G#A>GAG#$BG0G#
G	G#
G 	G##
G1)rT   rU   rS   r,   N)rF   rG   rH   rI   r7   rb   rJ   rK   r!   r   rM   rM   N   s    !<r!   rM   c                        \ rS rSrS rS rSrg)BaseTestCaseo   c                 8    [         R                  " 5       U l        g rC   )r   threading_setup_threadsr5   s    r   setUpBaseTestCase.setUpp   s    (88:r!   c                 z    [         R                  " U R                  6   [        R                  R                  5         g rC   )r   threading_cleanupri   r   r   reap_childrenr5   s    r   tearDownBaseTestCase.tearDowns   s$    **DMM:""$r!   )ri   N)rF   rG   rH   rI   rj   ro   rJ   rK   r!   r   re   re   o   s    ;%r!   re   c                      \ rS rSrSr\S 5       rS rS rS r	S r
S rS	 rS
 rS rS rS rS rS rS rS rS r\R.                  " SSSS9S 5       rS rS rS rS rS r\S 5       r\S 5       r S r!\\"RF                  " \$" \%S 5      S!5      S" 5       5       r&\\"RF                  " \$" \%S 5      S!5      S# 5       5       r'\\"RF                  " \$" \%S 5      S!5      S;S$ j5       5       r(S;S% jr)S& r*S' r+S( r,S) r-\S* 5       r.S+ r/S, r0S- r1S. r2S/ r3S0 r4S1 r5S2 r6S3 r7S4 r8\\"RF                  " \$" \9S55      S65      S7 5       5       r:\S8 5       r;S9r<g:)<ThreadTestsx   i'  c                    S n[         R                  " SS9nU R                  UR                  S5        [         R                  " SS9nU R                  UR                  S5        [         R                  " USS9nU R                  UR                  S5        [        R
                  R                  [         SS	S
9   [         R                  " SS9nU R                  UR                  S5        S S S 5        [        R
                  R                  [         SSS
9   [         R                  " 5       nU R                  UR                  S5        S S S 5        [        R
                  R                  [         SSS
9   [         R                  " US9nU R                  UR                  S5        S S S 5        g ! , (       d  f       N= f! , (       d  f       N|= f! , (       d  f       g = f)Nc                      g rC   rK   rK   r!   r   func#ThreadTests.test_name.<locals>.func}       Dr!   myname1rP   {   123myname2)targetrQ   _counter   )return_value zThread-2rX   zThread-3   r}   zThread-5 (func))r*   rR   assertEqualrQ   r   patchobject)r6   rv   r   s      r   	test_nameThreadTests.test_name{   sd   !!y1i0 !!s+e, !!I>i0ZZy*1E%%2.FV[[*5 F ZZy*1E%%'FV[[*5 F ZZy*1E%%T2FV[[*;< FE FE FE FEs$   81F+2F<11G+
F9<
G

Gc                 R  ^  S/nSnS/nSnS/4nS/nUU 4S j4UU 4S j4UU 4S j4UU 4S j4UU 4S	 j4UU 4S
 j44nU HQ  u  pT R                  XS9   [        R                  " XS9n
U
R                  5         U
R	                  5         S S S 5        MS     g ! , (       d  f       Me  = f)Nr;   r;   strr   c                 (   > TR                  U S5      $ r:   r   argr6   s    r   <lambda>0ThreadTests.test_args_argument.<locals>.<lambda>   s    4#3#3C#;r!   c                 (   > TR                  U S5      $ r:   r   r   s    r   r   r      s    D$4$4S!$<r!   c                 (   > TR                  U S5      $ Nr   r   r   s    r   r   r      s    4#3#3C#?r!   c                 (   > TR                  U S5      $ r   r   r   s    r   r   r      s    D$4$4S%$@r!   c                 *   > TR                  U S/5      $ r:   r   r   s    r   r   r      s    (8(8qc(Br!   c                 (   > TR                  U S5      $ )Nr   r   r   s    r   r   r      s    (8(8d(Cr!   r}   args)subTestr*   rR   startjoin)r6   num_list	num_tuplestr_list	str_tuplelist_in_tupletuple_in_list
test_casesr   r}   ts   `          r   test_args_argumentThreadTests.test_args_argument   s     3	7	 ;<<=?@@ABCCD

 'LDV7$$F>	 87 '77s   5B
B&	c           	      
   [         R                  " 5         U R                  [        [         R                  S5        U R                  [        [         R                  SS9  U R                  [        [         R                  SSSSS9  g )Nr;   )ar   )r   b)r*   LockassertRaises	TypeErrorr5   s    r   test_lock_no_argsThreadTests.test_lock_no_args   sZ    )Y^^Q7)Y^^q9)Y^^QQ!Dr!   c                     U R                  [        5          " S S[        R                  5      nS S S 5        g ! , (       d  f       g = f)Nc                       \ rS rSrSrg)1ThreadTests.test_lock_no_subclass.<locals>.MyLock   rK   NrF   rG   rH   rI   rJ   rK   r!   r   MyLockr      s    $r!   r   )r   r   r*   r   )r6   r   s     r   test_lock_no_subclass!ThreadTests.test_lock_no_subclass   s*     y).. *))s	   9
Ac                 f    SS K nU R                  [        R                  S -  UR                  5        g r2   )typesassertIsInstancer*   r   	UnionType)r6   r   s     r   test_lock_or_noneThreadTests.test_lock_or_none   s"    innt3U__Er!   c                    Sn[         R                  " SS9n[         R                  " 5       n[        5       n/ n[	        U5       Hj  n[        SU-  XX45      nUR                  U5        U R                  UR                  5        U R                  [        U5      S5        UR                  5         Ml     [        [         S5      (       aY  [        S U 5       5      [         R                  " 5       1-  nU R                  S U5        U R!                  [#        U5      US-   5        [$        (       a  ['        S	5        U H  nUR)                  5         U R+                  UR-                  5       5        U R/                  UR                  S
5        U R1                  UR                  5        U R                  [        U5      S5        M     [$        (       a  ['        S5        U R!                  UR3                  5       S
5        g )N
   rX   r3   z<thread %d>z^<TestThread\(.*, initial\)>$get_native_idc              3   8   #    U  H  oR                   v   M     g 7frC   )	native_id).0r   s     r   	<genexpr>/ThreadTests.test_various_ops.<locals>.<genexpr>   s     :'Q[['s   r;   z!waiting for all tasks to completer   z#^<TestThread\(.*, stopped -?\d+\)>$zall tasks done)r*   BoundedSemaphoreRLockr/   rangerM   appendassertIsNoneidentassertRegexreprr   hasattrsetr   assertNotInr   lenr   r\   r   assertFalseis_aliveassertNotEqualassertIsNotNonerD   )	r6   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                 v  ^^ U R                  [        R                  " 5       R                  5        UU4S jn[        R                  " 5       m/ m[
        R                  " 5          [        R                  " US5      nTR                  5         U R                  TS   U5        S S S 5        g ! , (       d  f       g = f)Nc                     > TR                  [        R                  " 5       R                  5        T R	                  5         g rC   )r   r*   current_threadr   r   )rZ   r   s   r   f9ThreadTests.test_ident_of_no_threading_threads.<locals>.f   s'    LL11399:HHJr!   rK   r   )r   r*   r   r   Eventr   wait_threads_exit_threadstart_new_threadwaitr   )r6   r   tidrZ   r   s      @@r   "test_ident_of_no_threading_threads.ThreadTests.test_ident_of_no_threading_threads   s    Y557==>	  //1**1b1CIIKU1Xs+ 211s   $=B**
B8c                    [         (       a  [        S5         [        R                  " S5        U R                  5         [        R                  " S5        g ! [        R
                   a    [        R                  " S5      ef = f)Nz!with 256 KiB thread stack size...i   4platform does not support changing thread stack sizer   	r   r\   r*   
stack_sizer   errorr   SkipTestr   r5   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                    [         (       a  [        S5         [        R                  " S5        U R                  5         [        R                  " S5        g ! [        R
                   a    [        R                  " S5      ef = f)Nzwith 1 MiB thread stack size...i   r   r   r   r5   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                   ^ ^^ S mS mUUU 4S jn[         R                  " 5       nUR                  5         [        R                  " 5          [
        R                  " X45      nUR                  5         S S S 5        Tb  TeT R                  WTR                  5        T R                  [        5         TR                  5         S S S 5        TR                  R                  5         T R                  [        5         TR                  5         S S S 5        Sn[        R                   " 5       U-   n[        R                   " 5       U:  a^  [         R"                  R%                  TR                  5      TLa  g [        R&                  " S5        [        R                   " 5       U:  a  M^  T R)                  S5        g ! , (       d  f       GNI= f! , (       d  f       GN= f! , (       d  f       N= f)Nc                   >  [         R                  " 5       mTR                  nTR                  U[         R                  5        TR                  T[         R                  5        TR                  [         R                  R                  U5      T5        TR                  TR                  5       S5        TR                  S[        T5      5        U R                  5         g ! [         a  nUm S nAN"S nAff = f! U R                  5         f = f)Nz-Expected _DummyThread to be considered alive._DummyThread)r*   r   r   assertIn_activer   r   assertIsrD   
assertTruer   r   BaseExceptionrelease)rT   r   edummy_threadr   r6   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 
C5)C0+C8 0C55C8 8D
r   皙?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   rD   r_   fail)r6   r   rT   r   timeout
timeout_atr   r   s   `     @@r   test_foreign_threadThreadTests.test_foreign_thread  sW   	 ,  //1**1h7CMMO 2 Kl001|, -##%|,!!# - ^^%/
nn+  $$\%7%78LJJrN nn+
 IIst- 21 -, -,s$   
(F40G8G4
G
G
G&c                 f  ^	^
^ [        S5      nUR                  R                  nUR                  UR                  4Ul         " S S[        5      m	UR	                  T	5      n[        R                  " 5       nU R                  U[        5        U R                  US5         U" XC5      n  M  ! T	 a     Of = f U R                  WS5        O! [         a     Of = f[        R                  " 5       m[        R                  " 5       m
 " U	U
U4S jS[        R                   5      nU" 5       nSUl        UR%                  5         [&        (       a  [)        S	5        [&        (       a  [)        S
5        U" SU5      nU R                  US5        [&        (       a  [)        S5        TR+                  5       nU R-                  U5        [&        (       a  [)        S5        U R/                  UR0                  5        [&        (       a  [)        S5        U" UR2                  U5      nU R                  US5        [&        (       a  [)        S5        T
R+                  [4        R6                  S9  U R-                  UR0                  5        [&        (       a  [)        S5        UR0                  (       a  UR9                  5         g g )Nctypesc                       \ rS rSrSrg)<ThreadTests.test_PyThreadState_SetAsyncExc.<locals>.AsyncExciH  rK   Nr   rK   r!   r   AsyncExcr  H  s    r!   r  r   Tr;   c                   &   > \ rS rSrU UU4S jrSrg):ThreadTests.test_PyThreadState_SetAsyncExc.<locals>.Workerik  c                    > [         R                  " 5       U l        SU l          TR	                  5         [
        R                  " S5        M(  ! T a    SU l        TR	                  5          g f = f)NFTr  )r*   	get_identidfinishedr   r^   r_   )r6   r  worker_saw_exceptionworker_starteds    r   rb   >ThreadTests.test_PyThreadState_SetAsyncExc.<locals>.Worker.runl  sb    #--/ %/&**,

3    /$(DM(,,./s   )A A-,A-)r  r  NrF   rG   rH   rI   rb   rJ   )r  r  r  s   r   Workerr  k  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 worker)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   )r6   r  set_async_exc	exceptionr   resultr  r   retr  r  r  s            @@@r   test_PyThreadState_SetAsyncExc*ThreadTests.test_PyThreadState_SetAsyncExcB  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                 <   S n[         R                  nU[         l         [         R                  " S S9nU R                  [         R                  UR
                  5        U R                  U[         R                  ;   S5        U[         l        g ! U[         l        f = f)Nc                  ,    [         R                  " 5       erC   )r*   ThreadErrorr   kwargss     r   fail_new_thread7ThreadTests.test_limbo_cleanup.<locals>.fail_new_thread  s    ''))r!   c                      g rC   rK   rK   r!   r   r   0ThreadTests.test_limbo_cleanup.<locals>.<lambda>      r!   r   z:Failed to cleanup _limbo map on failure of Thread.start().)r*   _start_joinable_threadrR   r   r2  r   r   _limbo)r6   r5  r:  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                     [         R                  " SS9(       a  U R                  S5        [        S5        [	        SS5      u  pnU R                  US5        g )NTr   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)
            *   )r   r   skipTestr	   r   r   r6   rcouterrs       r   test_finalize_running_thread(ThreadTests.test_finalize_running_thread  sP     ""$/ MM9:h,T 4 2 	R r!   c                 p    [         R                  " SS9(       a  U R                  S5        [        SS5        g )NTr   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)
            )r   r   rB  r
   r5   s    r   test_finalize_with_trace$ThreadTests.test_finalize_with_trace  s0     ""$/ MM9:   	r!   c                     [        SS5      u  pnU R                  UR                  5       S5        U R                  US5        g )Nr@  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!   r
   r   striprC  s       r   test_join_nondaemon_on_shutdown+ThreadTests.test_join_nondaemon_on_shutdown  sE     ( /  	D	Fc"r!   c                    [         R                  n[        R                  " 5       n [	        SS5       Hn  n[
        R                  " US-  5        [         R                  " S S9nUR                  5         UR                  5         U" 5       nU R                  XESX54-  5        Mp     [        R                  " U5        g ! [        R                  " U5        f = f)Nr;   d   g-C6*?c                      g rC   rK   rK   r!   r   r   7ThreadTests.test_enumerate_after_join.<locals>.<lambda>  s    Dr!   r   z&#1703448 triggered after %d trials: %s)r*   	enumerater   getswitchintervalr   r   setswitchintervalrR   r   r   r   )r6   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   A>B< <C   i  Fsizememusedry_runc           	        ^ / mS nU4S jn[        SS5       H  n[        R                  " US9/n[        U5       H+  nUR                  [        R                  " UUS   4S95        M-     U H  nUR	                  5         M     [
        R                  " S5        U H  nUR                  5         M     T(       d  M  TS   e   g )	Nc                  0    [         R                  " S5        g )Ng{Gzt?r^   r_   rK   r!   r   worker;ThreadTests.test_join_from_multiple_threads.<locals>.worker  s    JJur!   c                 x   >  U R                  5         g ! [         a  nTR                  U5         S nAg S nAff = frC   )r   r$  r   )r   r   errorss     r   joiner;ThreadTests.test_join_from_multiple_threads.<locals>.joiner  s0    ! !a  !s    
949r   r]  r   r   r   {Gz?)r   r*   rR   r   r   r^   r_   r   )	r6   r_  re  ri  Nr   r   r   rh  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                 ^  ^ [         R                  " 5       mTR                  5         U4S jn[        R                  " US9nUR                  5         UR                  SS9  UR                  5       (       d   eTR                  5         UR                  5         UR                  5       (       a   eg )Nc                  &   > T R                  5         g rC   )r  )locks   r   re  2ThreadTests.test_join_with_timeout.<locals>.worker0  s    LLNr!   r   rk  r  )	r   allocate_lockr  r*   rR   r   r   r   r   )r6   re  r   rq  s      @r   test_join_with_timeout"ThreadTests.test_join_with_timeout,  s    $$&	 !!0D!    ??$$$$$r!   c                     " S S[         5      n[        U 5        U" SS9n[        R                  " U5      nUR                  R                  5         AU R                  U" 5       S[        R                  " U" 5       5      -  S9  U" SS9n[        R                  " U5      nUR                  R                  5         AU R                  U" 5       S[        R                  " U" 5       5      -  S9  g )Nc                        \ rS rSrS rS rSrg)DThreadTests.test_no_refcycle_through_target.<locals>.RunSelfFunctioni<  c                     Xl         [        R                  " U R                  U 4SU 0S9U l        U R                  R                  5         g )Nyet_another)r}   r   r4  )should_raiser*   rR   _runr   r   )r6   r{  s     r   r7   MThreadTests.test_no_refcycle_through_target.<locals>.RunSelfFunction.__init__=  sB     %1!'..dii59G7DT6JL !!#r!   c                 2    U R                   (       a  [        eg rC   )r{  
SystemExit)r6   	other_refrz  s      r   r|  IThreadTests.test_no_refcycle_through_target.<locals>.RunSelfFunction._runF  s    $$$$ %r!   )r{  r   N)rF   rG   rH   rI   r7   r|  rJ   rK   r!   r   RunSelfFunctionrx  <  s    $%r!   r  F)r{  z%d references still around)msgT)	r   r-   weakrefrefr   r   r   r   getrefcount)r6   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                    [         R                  " 5       nU R                  [        S5         UR	                  5         S S S 5        U R                  [        S5         UR                  S5        S S S 5        U R                  [        S5         UR                  5         S S S 5        U R                  [        S5         UR                  S5        S S S 5        [         R                  " 5       nU R                  [        S5         UR                  5         S S S 5        [         R                  " 5       nUR                  5         U R                  [        S5         UR                  5         S S S 5        U R                  [        S	5         [         R                  " 5         S S S 5        U R                  [        S
5         [         R                  " 5         S S S 5        g ! , (       d  f       GN= f! , (       d  f       GN= f! , (       d  f       GNd= f! , (       d  f       GNF= f! , (       d  f       GN= f! , (       d  f       N= f! , (       d  f       N= f! , (       d  f       g = f)Nzget the daemon attributez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)r6   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GGI G ""$""#57IJNN K ""#57KL!!# M""#57MN##% ON1@ @@ @> >> >
 GF
 KJ MLNNs_   GG'G9:H?HH/I 6I
G$'
G69
H
H
H,/
H= 
I
Ic                     [         R                  " 5       nU R                  S[        U5      5        SUl        U R                  S[        U5      5        g Nr(  T)r*   rR   r   r   r(  r   r6   r   s     r   test_repr_daemonThreadTests.test_repr_daemon{  s=    47+hQ(r!   c                     [         R                  " 5       nU R                  UR                  5        [         R                  " SS9nU R                  UR                  5        [         R                  " SS9nU R	                  UR                  5        g )NF)r(  T)r*   rR   r   r(  r   r  s     r   test_daemon_paramThreadTests.test_daemon_param  sd    "E*"D)!r!   c                 n    Sn[        SU5      u  p#nU R                  US5        U R                  US5        g )Na  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!   r
   r   r6   code_rE  rF  s        r   test_dummy_thread_after_fork(ThreadTests.test_dummy_thread_after_fork  s;    0 'tT2c"c"r!   c                 ^   [         R                  " 5       nU R                  [         R                  U5        [        R
                  R                  S5        [        S5       H  n[        R                  " S S9nUR                  5         [        R                  " [        SS9   [        R                  " 5       =nS:X  a.  [        R                  " UR!                  5       (       a  SOS	5        O%UR#                  5         [
        R$                  " US	S
9  S S S 5        M     g ! , (       d  f       M  = f)Ngư>r]  c                      g rC   rK   rK   r!   r   r   6ThreadTests.test_is_alive_after_fork.<locals>.<lambda>  r9  r!   r   ignorecategoryactionr      r   exitcode)r   rV  r(   rW  r   r   r   r*   rR   r   warningscatch_warningsr  osfork_exitr   r   wait_process)r6   rY  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/D
D,	c                   ^  [         R                  " 5       nT R                  UR                  S5        T R                  UR                  [         R
                  " 5       R                  5        T R                  UR                  [         R                  " 5       5        U 4S jn[         R                  " US9nUR                  5         UR                  5         g )N
MainThreadc                     > T R                  [        R                  " 5       R                  [        R                  " 5       R                  5        g rC   )r   r*   main_threadr   r   r5   s   r   r   'ThreadTests.test_main_thread.<locals>.f  s5    	 5 5 7 = = ) 8 8 : @ @Br!   r   )
r*   r  r   rQ   r   r   r  rR   r   r   )r6   mainr   ths   `   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                     Sn[        SU5      u  p#nUR                  5       R                  SS5      nU R                  US5        U R                  US5        g )Na!  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
r
   decodereplacer   r6   r  r  rE  rF  datas         r   test_main_thread_after_fork'ThreadTests.test_main_thread_after_fork  sX     'tT2zz|##D"-c"2	3r!   c                     Sn[        SU5      u  p#nUR                  5       R                  SS5      nU R                  UR                  S5      S5        U R                  US5        g )Na  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
r  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                     SU-  n[        SSSU5      u  p4nUR                  5       R                  SS5      nU R                  UR                  5       S5        U R                  UU(       a  SOSSU< S	3-   S
-   5        g )NaC  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']
r  )r6   create_dummyr  r  rE  rF  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                 "    U R                  SS9  g )NT)r  )r  )r6   r  s     r   -test_main_thread_after_fork_from_dummy_thread9ThreadTests.test_main_thread_after_fork_from_dummy_threadQ  s    <<$<Or!   c                     Sn[        SU5      u  p#nUR                  5       nU R                  US5        U R                  UR                  5       S/S-  5        g )Na  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 Truer   )r
   r  r   
splitlinesr  s         r    test_main_thread_during_shutdown,ThreadTests.test_main_thread_during_shutdownT  sX    ( 'tT2zz|c"*./!3	5r!   c                 J    Sn[        SU5      u  p#nU R                  US5        g )Na  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!   r  r6   r  rD  rE  rF  s        r   test_finalization_shutdown&ThreadTests.test_finalization_shutdownq  s+    4 (d3c"r!   c                 4  ^^ [         R                  " 5       m[         R                  " 5       mTR                  5         TR                  5         UU4S jn[        R                  " US9nUR                  5         TR                  5         U R                  S[        U5      5        TR                  5         Sn[        S5       H*  nU[        U5      ;   a    O[        R                  " S5        M,     U R                  U[        U5      5        UR                  5         g )Nc                  F   > TR                  5         T R                  5         g rC   )r   r  )finishstarteds   r   r   (ThreadTests.test_repr_stopped.<locals>.f  s    OONNr!   r   r  stoppedi  rk  )r   rs  r  r*   rR   r   r   r   r   r   r^   r_   r   )r6   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                 R   [        SS5       GH  n[        R                  " U5      n[        U5       Vs/ s H!  n[        R                  " UR                  S9PM#     nnU H  nUR                  5         M     U H  nUR                  5         M     [        U5       Vs/ s H!  n[        R                  " UR                  S9PM#     nnU H  nUR                  5         M     U H  nUR                  5         M     U R                  [        UR                  5        GM     g s  snf s  snf )Nr;   r   r   )
r   r*   r   rR   r  r   r   r   r   
ValueError)r6   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                   ^^^ [        S5      nU4S jmS mUU4S jmS Tl        [        R                  " 5       n[        R                  " T5         [
        R                  " T5        UR                  T5        [        S5       H
  nT" 5         M     [        R                  " U5        [
        R                  " U5        g ! [        R                  " U5        [
        R                  " U5        f = f)N	_testcapic                    > T$ rC   rK   frameeventr   
noop_traces      r   r  9ThreadTests.test_frame_tstate_tracing.<locals>.noop_trace  	    r!   c               3      #     Sv   M  7f)N	generatorrK   rK   r!   r   r  8ThreadTests.test_frame_tstate_tracing.<locals>.generator  s     !! s   
c                  `   > T R                   c  T" 5       T l         [        T R                   5      $ rC   )gennext)callbackr  s   r   r  7ThreadTests.test_frame_tstate_tracing.<locals>.callback  s%    ||#({%%r!   rX   )r	   r  r   gettracesettracer*   call_in_temporary_c_threadr   )r6   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 B? ?.C-c                   ^ U4S jm[         R                  " 5       n [         R                  " T5        [         R                  " 5       nU R                  TU5        [         R                  " U5        g ! [         R                  " U5        f = f)Nc                    > T$ rC   rK   r  s      r   r  -ThreadTests.test_gettrace.<locals>.noop_trace  r  r!   )r*   r  r  r   )r6   r  
trace_funcr  s      @r   test_gettraceThreadTests.test_gettrace  sf    	 &&(		*z*"++-JZ
3y)Iy)s   =A2 2B
c                 *  ^^^ S n[         R                  " 5       n[         R                  " 5       m[         R                  " 5       m/ mUUU4S jn [         R                  " US9nUR	                  5         TR                  5         [         R                  " U5        TR                  5         UR                  5         U R                  TS U/5        U R                  [         R                  " 5       U5        U R                  [        R                  " 5       U5        [         R                  " U5        U R                  [         R                  " 5       U5        U R                  [        R                  " 5       U5        g ! [         R                  " U5        f = f)Nc                      g rC   rK   r   s    r   fn1ThreadTests.test_gettrace_all_threads.<locals>.fn      tr!   c                     > TR                  [        R                  " 5       5        T R                  5         TR	                  5         TR                  [        R                  " 5       5        g rC   )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   )r*   r  r   rR   r   r   settrace_all_threadsr   r   r   r   )r6   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                    S n[         R                  " 5       n [         R                  " U5        U R                  U[         R                  " 5       5        [         R                  " U5        g ! [         R                  " U5        f = f)Nc                      g rC   rK   r  s    r   r  'ThreadTests.test_getprofile.<locals>.fn  r  r!   )r*   
getprofile
setprofiler   )r6   r  old_profiles      r   test_getprofileThreadTests.test_getprofile  s\    **,	.  $R!5!5!78  -I  -s   ;A, ,Bc                 *  ^^^ S n[         R                  " 5       n[         R                  " 5       m[         R                  " 5       m/ mUUU4S jn [         R                  " US9nUR	                  5         TR                  5         [         R                  " U5        TR                  5         UR                  5         U R                  TS U/5        U R                  [         R                  " 5       U5        U R                  [        R                  " 5       U5        [         R                  " U5        U R                  [         R                  " 5       U5        U R                  [        R                  " 5       U5        g ! [         R                  " U5        f = f)Nc                      g rC   rK   r  s    r   r  3ThreadTests.test_getprofile_all_threads.<locals>.fn  r  r!   c                     > TR                  [        R                  " 5       5        T R                  5         TR	                  5         TR                  [        R                  " 5       5        g rC   )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   )r*   r$  r   rR   r   r   setprofile_all_threadsr   r   r   r   )r6   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                 b    [        SS5      u  pnU R                  UR                  5       S5        g )Nr@  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')r
   r   rstriprC  s       r   test_locals_at_exitThreadTests.test_locals_at_exit9  s2     ( /  	'FGr!   c                      " S S[         5      nU" 5       n[        R                  " US9nUR                  5         UR	                  5         U R                  UR                  5        g )Nc                   &    \ rS rSrS rS rS rSrg)6ThreadTests.test_boolean_target.<locals>.BooleanTargetiO  c                     SU l         g NFranr5   s    r   r7   ?ThreadTests.test_boolean_target.<locals>.BooleanTarget.__init__P  s	     r!   c                     gr:  rK   r5   s    r   __bool__?ThreadTests.test_boolean_target.<locals>.BooleanTarget.__bool__R  s    r!   c                     SU l         g )NTr;  r5   s    r   __call__?ThreadTests.test_boolean_target.<locals>.BooleanTarget.__call__T  s	    r!   r;  N)rF   rG   rH   rI   r7   r?  rB  rJ   rK   r!   r   BooleanTargetr8  O  s    ! r!   rD  r   )r   r*   rR   r   r   r   r<  )r6   rD  r}   r   s       r   test_boolean_targetThreadTests.test_boolean_targetJ  sI    
	 F 	  !!0

#r!   c                     S n[         R                  " 5          [        R                  " US9R	                  5         S S S 5        g ! , (       d  f       g = f)Nc                      g rC   rK   rK   r!   r   noop0ThreadTests.test_leak_without_join.<locals>.noop`  rx   r!   r   )r   r   r*   rR   r   )r6   rI  s     r   test_leak_without_join"ThreadTests.test_leak_without_join]  s6     	//1D)//1 211s   #A
Ac                     [         R                  " S5      n[        SU5      u  p#nU R                  US5        U R                  US5        g )Na  
            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!   )textwrapdedentr
   r   r  s        r   test_import_from_another_thread+ThreadTests.test_import_from_another_threade  sI        2 (d3c"c"r!   c                     Sn[        SU5      u  p#nU R                  UR                  5       S5        U R                  SU5        g )Na6  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 shutdown)r
   r   rN  r   r  s        r   %test_start_new_thread_at_finalization1ThreadTests.test_start_new_thread_at_finalization  s@     'tT2e,H#Nr!   c                      SSK JnJn  Sn[        SSU5      u  pVnUR                  5       nSU;   a  U R	                  S5        U R                  US5        U R                  US	5        g ! [         a  nU R	                  U5         S nAN~S nAff = f)
Nr   )	setrlimitRLIMIT_NPROCa  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  ImportErrorrB  r
   rN  r   )r6   rW  rX  rF  r  r  rE  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2BBr   z$test needs threading.get_native_id()c                    Sn[        SU5      u  p#nU R                  US5        U R                  US5        UR                  5       R                  5       nU R                  [	        U5      S5        U R                  US   US   5        g )NaB  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   r!   r   r;   )r
   r   rN  r  r   r   )r6   scriptrD  rE  rF  r   s         r   test_native_id_after_fork%ThreadTests.test_native_id_after_fork  s{    & (f5Qc"YY[++-
Z!,JqM:a=9r!   c                     [         R                  " SSS9(       a  U R                  S5        [        R                  " S5      n[        SU5        g )NT)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@  )r   r   rB  rN  rO  r
   r6   r^  s     r    test_finalize_daemon_thread_hang,ThreadTests.test_finalize_daemon_thread_hang  sG    ""$t< MM<=  :" :v 	v&r!   rK   N)F)=rF   rG   rH   rI   maxDiffr   r   r   r   r   r   r   r   r   r   r  r.  r<  rG  rJ  rO  r[  r   
bigmemtestrm  rt  r  r  r  r  r    r  r  r  r   
skipUnlessr   r  r  r  r  r  r  r  r  r  r	  r  r  r'  r0  r4  rE  rK  rP  rT  r[  r*   r_  rd  rJ   rK   r!   r   rr   rr   x   s   G= =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"!#H O<>de: f :6 C' C'r!   rr   c                       \ rS rSrS rS r\S 5       r\S 5       r\	R                  " \R                  \;   S5      \R                  " SSS	S
9S 5       5       rS r\S 5       r\S 5       rSrg)ThreadJoinOnShutdowni  c                     SU-   n[        SU5      u  p#nUR                  5       R                  SS5      nU R                  US5        g )Na  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
r  )r6   r^  rD  rE  rF  r  s         r   _run_and_join"ThreadJoinOnShutdown._run_and_join!  sN    
 
 (f5zz|##D"-=>r!   c                 *    SnU R                  U5        g )Nzif 1:
            import os
            t = threading.Thread(target=joiningfunc,
                                 args=(threading.current_thread(),))
            t.start()
            time.sleep(0.1)
            print('end of main')
            rl  rc  s     r   test_1_join_on_shutdown,ThreadJoinOnShutdown.test_1_join_on_shutdown2  s     	6"r!   c                 *    SnU R                  U5        g )Na  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')
            ro  rc  s     r   test_2_join_in_forked_process2ThreadJoinOnShutdown.test_2_join_in_forked_process>  s     	6"r!   c                 *    SnU R                  U5        g )Na  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()
            ro  rc  s     r   !test_3_join_in_forked_from_thread6ThreadJoinOnShutdown.test_3_join_in_forked_from_threadR  s    
* 	6"r!   zdue to known OS bug(   i  `Fr^  c                     [         R                  " SS9(       a  U R                  S5        Sn[        SU5      u  p4nU R	                  U5        g )NTr   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@  )r   r   rB  r
   r   )r6   r_  r^  rD  rE  rF  s         r   test_4_daemon_threads*ThreadJoinOnShutdown.test_4_daemon_threadsn  sI     ""$/ MM9:!D (f5r!   c                     Sn[        SU5      u  p#nU R                  US5        U R                  UR                  5       S5        U R                  US5        g )Na  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!   rS  r   rM  r6   r^  rD  rE  rF  s        r   test_thread_from_thread,ThreadJoinOnShutdown.test_thread_from_thread  sQ    $ (f5c"e,Qr!   c                 4   S n[         R                  " [        SS9   / n[        S5       H8  n[        R
                  " US9nUR                  U5        UR                  5         M:     U H  nUR                  5         M     S S S 5        g ! , (       d  f       g = f)Nc                      [         R                  " 5       n U S:  a  [        R                  " U SS9  g [         R                  " S5        g )Nr   2   r  )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   )	r  r  r  r   r*   rR   r   r   r   )r6   r  r   r   r   s        r   test_reinit_tls_after_fork/ThreadJoinOnShutdown.test_reinit_tls_after_fork  s}    
	 $$.@,46 G2Y$$,<=q!	 
  6 6 6s   A#B		
Bc                 n   / n[        S5       H9  n[        R                  " S S9nUR                  U5        UR	                  5         M;      [
        R                  " [        SS9   [        R                  " 5       nUS:X  aP  [        [        R                  " 5       5      S:X  a  [        R                  " S5        O,[        R                  " S	5        O[        R                  " USS
9  S S S 5        U H  nUR!                  5         M     g ! , (       d  f       N(= f! U H  nUR!                  5         M     f = f)Nr  c                  .    [         R                  " S5      $ )Ng333333?rd  rK   r!   r   r   KThreadJoinOnShutdown.test_clear_threads_states_after_fork.<locals>.<lambda>  s    Cr!   r   r  r  r   r;   3   4   r  )r   r*   rR   r   r   r  r  r  r  r  r   r   _current_framesr  r   r  r   )r6   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 %BD&D 
DD D4rK   N)rF   rG   rH   rI   rl  rp  r    rs  rv  r   r#   r   r   r   r   rg  rz  r~  r  r  rJ   rK   r!   r   rj  rj    s    ?"
# # #& # #6 __S\\%668MNR%@, A O,\ 0  2  r!   rj  c                   |    \ rS rSrS rS rS r\S 5       r\	S 5       r
SSSSS	.S
 jjr\	S 5       r\	S 5       rSrg)SubinterpThreadingTestsi  c                    [         R                  " 5       u  pU R                  [         R                  U5        U R                  [         R                  U5        [	        [         S5      (       a  [         R
                  " US5        X4$ )Nset_blockingF)r  piper(   closer   r  )r6   rws      r   r  SubinterpThreadingTests.pipe  sU    wwy!$!$2~&&OOAu%vr!   c                    U R                  5       u  p[        R                  " SU4-  5      n[        R                  R                  U5      nU R                  US5        U R                  [        R                  " US5      S5        g )Na  
            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()
        r   r;      x	r  rN  rO  r   r   run_in_subinterpr   r  readr6   r  r  r  r-  s        r   test_threads_join)SubinterpThreadingTests.test_threads_join  sp     yy{  $ d%  & ll++D1a A-r!   c                    U R                  5       u  p[        R                  " SU4-  5      n[        R                  R                  U5      nU R                  US5        U R                  [        R                  " US5      S5        g )Na  
            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   r;   r  r  r  s        r   test_threads_join_2+SubinterpThreadingTests.test_threads_join_2  sp    
 yy{  2 d3  4 ll++D1a A-r!   c                    U R                  5       u  pSnSnSn[        R                  " 5       nUR                  SU SU< SU SU< SU SU< S35        UR	                  5         U R                  [        R                  " US	5      U5        U R                  [        R                  " US	5      U5        U R                  [        R                  " US	5      U5        g )
N   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()
            r;   )r  r   createexecr  r   r  r  )r6   r_interpw_interpINTERPFINIDONEinterps          r   test_threads_join_with_no_main6SubinterpThreadingTests.test_threads_join_with_no_main7  s    !YY[$$& 
 #2dX . #2dX . Zr& ,+ 	. 	1-v61-t41-t4r!   c                 2   [        S5        S[        R                  R                   S3nSU< S3n[        R                  R	                  5          [        SU5      u  p4nS S S 5        U R                  SWR                  5       5        g ! , (       d  f       N/= f)Nr  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@  z:Fatal Python error: Py_EndInterpreter: not the last thread)r	   r   r   r)  SuppressCrashReportr   r   r  )r6   subinterp_coder^  rD  rE  rF  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TFalloweddaemon_allowedr(  c                   [        S5        [        R                  " SU SU S35      n[        [        R
                  5      n[        R                  " SU< SU SU SU S	3	5      n[        R                  R                  5          [        S
U5      u    pS S S 5        U	R                  5       $ ! , (       d  f       W	R                  5       $ = f)N_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@  )
r	   rN  rO  boolr   Py_GIL_DISABLEDr   r  r
   r  )
r6   before_startr  r  r(  r  check_multi_interp_extensionsr^  r  rF  s
             r   _check_allowed&SubinterpThreadingTests._check_allowedu  s    
 	)*! .6
 7=X >N *  )-W-D-D(E% &  " #  'i (&&4%5 6//L.M N"  \\--/(v6IAq 0zz| 0/zz|s   B,,
C	c                 J    U R                  SSSS9nU R                  SU5        g )NFr  r  )r  r   r6   rF  s     r   test_threads_not_allowed0SubinterpThreadingTests.test_threads_not_allowed  s0    !!  " 

 	nc*r!   c                 >   U R                  S5         U R                  SSSS9nU R                  SU5        S S S 5        U R                  S5         U R                  SSSSS9nU R                  SU5        S S S 5        g ! , (       d  f       NM= f! , (       d  f       g = f)Nzvia Thread()TFr  r  z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%%!$	 & C MM.#. 65 *) 65s   $A=%B=
B
BrK   N)r   )rF   rG   rH   rI   r  r  r  r%   r  r   r  r  r  r  rJ   rK   r!   r   r  r    sw    .8#.J #5 #5J ; ;.#&*#B + + / /r!   r  c                   v    \ rS rSrS rS rS rS rS r\	" 5       S 5       r
S rS	 rS
 rS rS rS rS rSrg)ThreadingExceptionTestsi  c                     [         R                  " 5       nUR                  5         U R                  [        UR                  5        UR                  5         g rC   )r*   rR   r   r   r  r   r6   r   s     r   test_start_thread_again/ThreadingExceptionTests.test_start_thread_again  s6    !!#,5r!   c                 n    [         R                  " 5       nU R                  [        UR                  5        g rC   )r*   r   r   r  r   )r6   r   s     r   test_joining_current_thread3ThreadingExceptionTests.test_joining_current_thread  s&    "113,(;(;<r!   c                 n    [         R                  " 5       nU R                  [        UR                  5        g rC   )r*   rR   r   r  r   r  s     r   test_joining_inactive_thread4ThreadingExceptionTests.test_joining_inactive_thread  s$    !!#,4r!   c                     [         R                  " 5       nUR                  5         U R                  [        [
        USS5        UR                  5         g r  )r*   rR   r   r   r  r)   r   r  s     r   test_daemonize_active_thread4ThreadingExceptionTests.test_daemonize_active_thread  s8    !!#,4Hr!   c                 n    [         R                  " 5       nU R                  [        UR                  5        g rC   )r*   r   r   r  r   )r6   rq  s     r   test_releasing_unacquired_lock6ThreadingExceptionTests.test_releasing_unacquired_lock  s"    ~~,5r!   c                 t   SnSn[         R                  " [        R                  SU/[         R                  [         R                  S9nUR                  5       u  pEUR                  5       R                  SS5      nU R                  UR                  SSUR                  5       -   5        U R                  Xb5        g )	Na  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   r   zUnexpected error: )

subprocessPopenr   
executablePIPEcommunicater  r  r   
returncode)r6   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                     Sn[        SU5      u  p#nU R                  US5        UR                  5       nU R                  SU5        U R                  SU5        U R                  SU5        U R	                  SU5        g )Na  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 exceptionr
   r   r  r   r   r}  s        r   test_print_exception,ThreadingExceptionTests.test_print_exception  st    $ (f5c"jjl+S1:C@)3/.4r!   c                     Sn[        SU5      u  p#nU R                  US5        UR                  5       nU R                  SU5        U R                  SU5        U R                  SU5        U R	                  SU5        g )Na  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  r  r}  s        r   %test_print_exception_stderr_is_none_1=ThreadingExceptionTests.test_print_exception_stderr_is_none_1	  st    ( (f5c"jjl+S1:C@)3/.4r!   c                     Sn[        SU5      u  p#nU R                  US5        U R                  SUR                  5       5        g )Na  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  )r
   r   r   r  r}  s        r   %test_print_exception_stderr_is_none_2=ThreadingExceptionTests.test_print_exception_stderr_is_none_2&  sB    ( (f5c".

=r!   c                      Sn[        SU5        g )Na9  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@  )r   rc  s     r   test_print_exception_gh_1020566ThreadingExceptionTests.test_print_exception_gh_102056?  s    6 	dF+r!   c                   ^ S m " U4S jS[         R                  5      nU" 5       nUR                  5         UR                  5         U R	                  UR
                  5        U R                  UR
                  [        5        S Ul        g )Nc                      e rC   rK   rK   r!   r   
bare_raiseOThreadingExceptionTests.test_bare_raise_in_brand_new_thread.<locals>.bare_raise_  s    r!   c                   &   > \ rS rSrSrU 4S jrSrg)OThreadingExceptionTests.test_bare_raise_in_brand_new_thread.<locals>.Issue27558ib  Nc                 P   >  T" 5         g ! [          a  nXl         S nAg S nAff = frC   )r$  exc)r6   r  r  s     r   rb   SThreadingExceptionTests.test_bare_raise_in_brand_new_thread.<locals>.Issue27558.rune  s$    #L  #"HH#s    
% %)r  )rF   rG   rH   rI   r  rb   rJ   )r  s   r   
Issue27558r  b  s    C# #r!   r  )r*   rR   r   r   r   r  r   r  )r6   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                    S nU R                  [        R                  [        R                  5        [	        S5       Vs/ s H  n[
        R                  " US9PM     nnU H#  nUR                  5         UR                  5         M%     g s  snf )Nc                      [        [        R                  SSS9 n U R                  S5        [        R
                  " 5         S S S 5        g ! , (       d  f       g = f)Nr  r  )encoding )openr   TESTFNwrite	tracebackformat_stack)fps    r   modify_fileQThreadingExceptionTests.test_multithread_modify_file_noerror.<locals>.modify_fileu  s9    i&&g>"&&( ?>>s   'A


ArR  r   )	r(   r   unlinkr  r   r*   rR   r   r   )r6   r  r   r   r   s        r   $test_multithread_modify_file_noerror<ThreadingExceptionTests.test_multithread_modify_file_noerrors  sw    	)
 		(()*:*:; 3Z
 K0 	 
 AGGIFFH 	
s   B	c                     Sn[        SU5      u  p#nU R                  US5        U R                  US5        U R                  US5        g )Nzif True:
        import sys
        import threading

        threading.x = sys.modules[__name__]
        x = threading._DummyThread()
        r@  r   r!   r  r  s        r   )test_dummy_thread_on_interpreter_shutdownAThreadingExceptionTests.test_dummy_thread_on_interpreter_shutdown  sK    
 (d3Qc"c"r!   rK   N)rF   rG   rH   rI   r  r  r  r  r  r   r  r  r  r  r  r  r  r  rJ   rK   r!   r   r  r    sU    >56 0 0>565:>2,>* #r!   r  c                       \ rS rSrS rSrg)ThreadRunFaili  c                     [        S5      e)N
run failedr  r5   s    r   rb   ThreadRunFail.run  s    &&r!   rK   Nr  rK   r!   r   r  r    s    'r!   r  c                   ~   ^  \ rS rSrU 4S jr\S 5       r\R                  \S 5       5       r	S r
S rS rS rS	rU =r$ )
ExceptHookTestsi  c                 8   > [        U 5        [        TU ]	  5         g rC   )r-   superrj   )r6   	__class__s    r   rj   ExceptHookTests.setUp  s    "4(r!   c                    [         R                  " S5       n[        SS9nUR                  5         UR	                  5         S S S 5        WR                  5       R                  5       nU R                  SWR                   S3U5        U R                  SU5        U R                  SU5        U R                  SU5        g ! , (       d  f       N= f)	Nr  excepthook threadrP   Exception in thread :
#Traceback (most recent call last):
z   raise ValueError("run failed")zValueError: run failed)	r   captured_outputr  r   r   getvaluerN  r   rQ   )r6   r  r   s      r   test_excepthookExceptHookTests.test_excepthook  s    $$X.&"(;<FLLNKKM /
 "((*,V[[M=vF<fE8&A.7 /.s   *B>>
Cc                 B   [         R                  " S5       n [        S5      e! [         aW  n[        R
                  " / [        R                  " 5       QS P5      n [        R                  " U5        S n S nAO! S nf = fS nAff = f S S S 5        O! , (       d  f       O= fWR                  5       R                  5       nU R                  S[        R                  " 5        S3U5        U R                  SU5        U R                  SU5        U R                  SU5        g )Nr  bugr&  r'  r(  z  raise ValueError("bug")zValueError: bug)r   r)  r  r$  r*   ExceptHookArgsr   exc_infor'   r*  rN  r   r  )r6   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 A92B 4B9A==B  BB
B c                 $    " S S[         R                  5      n[        R                  " S5       nU" 5       nUR	                  5         UR                  5         S S S 5        U R                  WR                  5       S5        g ! , (       d  f       N/= f)Nc                       \ rS rSrS rSrg)4ExceptHookTests.test_system_exit.<locals>.ThreadExiti  c                 0    [         R                  " S5        g r:   )r   exitr5   s    r   rb   8ExceptHookTests.test_system_exit.<locals>.ThreadExit.run  s    r!   rK   Nr  rK   r!   r   
ThreadExitr5    s    r!   r9  r  r   )r*   rR   r   r)  r   r   r   r*  )r6   r9  r  r   s       r   test_system_exit ExceptHookTests.test_system_exit  sf    	)) 	
 $$X.&\FLLNKKM /
 	*B/ /.s   (B
Bc                   ^ S mU4S jn [         R                  " [        SU5         [        5       nUR	                  5         UR                  5         S S S 5        U R                  TR                  [        5        U R                  [        TR                  5      S5        U R                  TR                  TR                  R                  5        U R                  TR                  W5        S mg ! , (       d  f       N= f! S mf = f)Nc                 
   > U mg rC   rK   )	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   )r6   r?  r   r   s      @r   test_custom_excepthook&ExceptHookTests.test_custom_excepthook  s    		""9lDA& B
 T]]J7S0,?T//1M1MNMM$++v. D BA Ds#   C? +C.BC? .
C<8C? ?Dc                   ^ S nS mU4S jn[         R                  " [        SU5         [         R                  " [        SU5         [         R                  " S5       n[        5       nUR                  5         UR                  5         S S S 5        S S S 5        S S S 5        U R                  WR                  5       S5        U R                  TS5        g ! , (       d  f       NQ= f! , (       d  f       NZ= f! , (       d  f       Nc= f)Nc                     [        S5      e)Nthreading_hook failedr  r  s    r   threading_hookCExceptHookTests.test_custom_excepthook_fail.<locals>.threading_hook  s    455r!   c                    > [        U5      mg rC   r   )rB  rC  rD  err_strs      r   sys_hook=ExceptHookTests.test_custom_excepthook_fail.<locals>.sys_hook  s    )nGr!   r'   r  z#Exception in threading.excepthook:
rJ  )
r   rA  r*   r   r)  r  r   r   r   r*  )r6   rK  rO  r  r   rN  s        @r   test_custom_excepthook_fail+ExceptHookTests.test_custom_excepthook_fail  s    	6 	% y,GsL(;$$X.&"_FLLNKKM / < H 	*?	A"9: /. <; HGs;   C5C$+CC$C5
C!C$$
C2	.C55
Dc                 D   S nS nU" 5       n[         R                  " [        SU5         U" 5       n[        R                  [        l        U" 5       nS S S 5        U R                  UW5        U R                  UW5        U R                  US5        g ! , (       d  f       NE= f)Nc                      [         R                  " S5       n [        SS9nUR                  5         UR	                  5         S S S 5        U R                  5       $ ! , (       d  f       W R                  5       $ = f)Nr  r%  rP   )r   r)  r  r   r   r*  )outputr   s     r   
run_thread<ExceptHookTests.test_original_excepthook.<locals>.run_thread  s[    ((2f&,?@ 3 ??$$	 32 ??$$s   *A
A6c                 4    [        S[        R                  S9  g )NzRunning a thread failed)file)r\   r   r  r  s    r   rK  @ExceptHookTests.test_original_excepthook.<locals>.threading_hook  s    +#**=r!   r'   zRunning a thread failed
)r   rA  r*   r+   r'   r   r   )r6   rV  rK  default_outputcustom_hook_outputrecovered_outputs         r   test_original_excepthook(ExceptHookTests.test_original_excepthook  s    	%	> $y,G!+#,#;#;I )| H
 	)9:N,>?+-HI HGs   (B
BrK   )rF   rG   rH   rI   rj   r   r+  r   r   r1  r:  rF  rQ  r^  rJ   __classcell__r"  s   @r   r  r    sY     
8 
8 1  1(0*;*J Jr!   r  c                   &    \ rS rSrS rS rS rSrg)
TimerTestsi  c                 p    [         R                  U 5        / U l        [        R                  " 5       U l        g rC   )re   rj   callback_argsr*   r   callback_eventr5   s    r   rj   TimerTests.setUp  s'    4 'oo/r!   c                    [         R                  " SU R                  5      nUR                  5         U R                  R                  5         UR                  R                  S5        SUR                  S'   U R                  R                  5         [         R                  " SU R                  5      nUR                  5         U R                  R                  5         U R                  [        U R                  5      S5        U R                  U R                  S0 4S0 4/5        UR                  5         UR                  5         g )Nrk  blahbarfoor   rK   )r*   Timer_callback_spyr   rf  r   r   r   r4  r  r   r   re  r   )r6   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                     U R                   R                  US S  UR                  5       45        U R                  R	                  5         g rC   )re  r   copyrf  r   )r6   r   r4  s      r   rm  TimerTests._callback_spy'  s7    !!47FKKM":;!r!   )re  rf  N)rF   rG   rH   rI   rj   rp  rm  rJ   rK   r!   r   rc  rc    s    0
""r!   rc  c                   8    \ rS rSr\" \R                  5      rSrg)	LockTestsi+  rK   N)	rF   rG   rH   rI   staticmethodr*   r   locktyperJ   rK   r!   r   rv  rv  +  s    INN+Hr!   rv  c                   8    \ rS rSr\" \R                  5      rSrg)PyRLockTestsi.  rK   N)	rF   rG   rH   rI   rw  r*   _PyRLockrx  rJ   rK   r!   r   rz  rz  .  s    I../Hr!   rz  zRLock not implemented in Cc                   >    \ rS rSr\" \R                  5      rS rSr	g)CRLockTestsi1  c                 x   [         R                  " SS9 n[        R                  " 5         S S S 5        U R	                  W/ 5        S0 4SSS04SSS04/nU HQ  u  p4U R                  X4S9   U R                  [        5         [        R                  " U0 UD6  S S S 5        S S S 5        MS      " S	 S
U R                  5      n[         R                  " SS9 nU" SSS9  S S S 5        U R	                  U/ 5        g ! , (       d  f       N= f! , (       d  f       Nw= f! , (       d  f       M  = f! , (       d  f       NU= f)NT)recordr   rK   r   r;   )r;   r   r3  c                   ,   ^  \ rS rSrSU 4S jjrSrU =r$ )/CRLockTests.test_signature.<locals>.CustomRLockiE  c                "   > [         TU ]  5         g rC   )r!  r7   )r6   r   r   r"  s      r   r7   8CRLockTests.test_signature.<locals>.CustomRLock.__init__F  s     "r!   rK   )returnN)rF   rG   rH   rI   r7   rJ   r`  ra  s   @r   CustomRLockr  E  s    # #r!   r  r   )r   )	r  r  r*   r   r   r   assertWarnsr  rx  )r6   warnings_log	arg_typesr   r4  r  s         r   test_signatureCRLockTests.test_signature5  s   $$D1\OO 2r* 2J#qNc1X
	
 &LD47%%&89OOT4V4 : 87 &	#$-- 	# $$D1\Q 2r*+ 21 :9 87 21s;   C7*D DDD+7
D
DD
D(	+
D9rK   N)
rF   rG   rH   rI   rw  r*   _CRLockrx  r  rJ   rK   r!   r   r}  r}  1  s    I--.H+r!   r}  c                   8    \ rS rSr\" \R                  5      rSrg)
EventTestsiM  rK   N)	rF   rG   rH   rI   rw  r*   r   	eventtyperJ   rK   r!   r   r  r  M  s    Y__-Ir!   r  c                   >    \ rS rSr\" \R                  5      rS rSr	g)ConditionAsRLockTestsiP  c                 &    U R                  S5        g )Nz,Condition does not expose _recursion_count())rB  r5   s    r   test_recursion_count*ConditionAsRLockTests.test_recursion_countT  s    DEr!   rK   N)
rF   rG   rH   rI   rw  r*   r  rx  r  rJ   rK   r!   r   r  r  P  s    I//0HFr!   r  c                   8    \ rS rSr\" \R                  5      rSrg)ConditionTestsiW  rK   N)	rF   rG   rH   rI   rw  r*   r  condtyperJ   rK   r!   r   r  r  W  s    I//0Hr!   r  c                   8    \ rS rSr\" \R                  5      rSrg)SemaphoreTestsiZ  rK   N)	rF   rG   rH   rI   rw  r*   	SemaphoresemtyperJ   rK   r!   r   r  r  Z  s    9../Gr!   r  c                   8    \ rS rSr\" \R                  5      rSrg)BoundedSemaphoreTestsi]  rK   N)	rF   rG   rH   rI   rw  r*   r   r  rJ   rK   r!   r   r  r  ]  s    9556Gr!   r  c                   8    \ rS rSr\" \R                  5      rSrg)BarrierTestsi`  rK   N)	rF   rG   rH   rI   rw  r*   BarrierbarriertyperJ   rK   r!   r   r  r  `  s    y001Kr!   r  c                       \ rS rSrS rSrg)MiscTestCaseid  c                 ^    [        U 5        S1nSS1n[        R                  " U [        SXS9  g )Nr2  r  r  )r*   r   )extranot_exported)r-   r   check__all__r*   )r6   r  r  s      r   test__all__MiscTestCase.test__all__e  s4    "4('7T9.F#(	Er!   rK   N)rF   rG   rH   rI   r  rJ   rK   r!   r   r  r  d  s    Er!   r  c                   x    \ rS rSrS rS r\" S5      S 5       rS rS r	S r
S	 r\R                  S
 5       rSrg)InterruptMainTestsin  c                     S n[         R                   " X5      nU R                  [         R                   X5        U R                  [        5         [        R
                  " 5         S S S 5        g ! , (       d  f       g = f)Nc                     SS-    g )Nr;   r   rK   )signumr  s     r   handlerLInterruptMainTests.check_interrupt_main_with_signal_handler.<locals>.handlerp  s	    aCr!   )signalr(   r   r  r   interrupt_main)r6   r  r  old_handlers       r   (check_interrupt_main_with_signal_handler;InterruptMainTests.check_interrupt_main_with_signal_handlero  sP    	 mmF4v;01""$ 211s   A..
A<c                    [         R                  " U5      n [         R                   " U[         R                  5        [        R                  " U5        [         R                   " U[         R
                  5        [        R                  " U5        [         R                   " X5        g ! [         R                   " X5        f = frC   )r  	getsignalSIG_IGNr   r  SIG_DFL)r6   r  r  s      r   check_interrupt_main_noerror/InterruptMainTests.check_interrupt_main_noerrory  sr    ""6*		+MM&&..1""6*MM&&..1""6* MM&*FMM&*s   A6B% %B=z*gh-118433: Flaky due to a longstanding bugc                     S n[         R                  " US9nU R                  [        5         UR	                  5         UR                  5         S S S 5        UR                  5         g ! , (       d  f       N= f)Nc                  .    [         R                  " 5         g rC   )r   r  rK   r!   r   call_interruptHInterruptMainTests.test_interrupt_main_subthread.<locals>.call_interrupt  s    ""$r!   r   )r*   rR   r   KeyboardInterruptr   r   )r6   r  r   s      r   test_interrupt_main_subthread0InterruptMainTests.test_interrupt_main_subthread  sQ    	%N301GGIFFH 2 	
 21s   !A''
A5c                     U R                  [        5         [        R                  " 5         S S S 5        g ! , (       d  f       g = frC   )r   r  r   r  r5   s    r   test_interrupt_main_mainthread1InterruptMainTests.test_interrupt_main_mainthread  s+     01""$ 211s	   5
Ac                     U R                  [        R                  5        U R                  [        R                  5        g rC   )r  r  SIGINTSIGTERMr5   s    r   'test_interrupt_main_with_signal_handler:InterruptMainTests.test_interrupt_main_with_signal_handler  s&    55fmmD55fnnEr!   c                     U R                  [        R                  5        U R                  [        R                  5        g rC   )r  r  r  r  r5   s    r   test_interrupt_main_noerror.InterruptMainTests.test_interrupt_main_noerror  s&    ))&--8))&..9r!   c                     U R                  [        [        R                  S5        U R                  [        [        R                  [        R
                  5        U R                  [        [        R                  S5        g )Nr  i@B )r   r  r   r  r  NSIGr5   s    r   "test_interrupt_main_invalid_signal5InterruptMainTests.test_interrupt_main_invalid_signal  sN    *g&<&<bA*g&<&<fkkJ*g&<&<gFr!   c                     S/nS/nS/nS n[         R                  " XBX4S9nUR                  5         US   (       d   US   (       d  M  SUS'   UR                  5         U R	                  US   5        g )NTFc                 f    SnSU S'   US   (       a  U(       a  US-  nOg  US   (       a  M  SUS'   g )Ni Tr   r;   rK   )r  continterrupted
iterationss       r   re  AInterruptMainTests.test_can_interrupt_tight_loops.<locals>.worker  s?    $JGAJq'!OJ q'' "KNr!   r   r   )r*   rR   r   r   r   )r6   r  r  r  re  r   s         r   test_can_interrupt_tight_loops1InterruptMainTests.test_can_interrupt_tight_loops  ss    v'g		" F$0LM		!* !**Q	A'r!   rK   N)rF   rG   rH   rI   r  r  r   r  r  r  r  r  r   reap_threadsr  rJ   rK   r!   r   r  r  n  sW    %+ FG	 H	%F:G
 ""( #(r!   r  c                   &    \ rS rSrS rS rS rSrg)AtexitTestsi  c                     [        SS5      u  pnU R                  U5        U R                  UR                  5       S5        g )Nr@  zif True:
            import threading

            def run_last():
                print('parrot')

            threading._register_atexit(run_last)
        s   parrot)r
   r   r   rN  rC  s       r   test_atexit_outputAtexitTests.test_atexit_output  s=    ' /  	i0r!   c                 D    [        SS5      u  pnU R                  U5        g )Nr@  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()
        )r
   r   rC  s       r   test_atexit_called_once#AtexitTests.test_atexit_called_once  s'    ' 
/ 
 	r!   c                     [        SS5      u  pnU R                  U5        U R                  SUR                  5       5        g )Nr@  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 shutdown)r
   r   r   r  rC  s       r   test_atexit_after_shutdown&AtexitTests.test_atexit_after_shutdown  s?     ( 
/ 
 	J

	r!   rK   N)rF   rG   rH   rI   r  r  r  rJ   rK   r!   r   r  r    s    1r!   r  __main__)D__doc__test.supportr   r   r   r   r   r   r   test.support.import_helperr	   test.support.script_helperr
   r   r   r[   r   r   r*   r^   r   r  r  r  r  rN  r  r  r   r   r   r   rZ  requires_working_threadingr   r    r%   r-   r   r/   rR   rM   TestCasere   rr   rj  r  r  r  r  rc  rv  
RLockTestsrz  r#   r  r}  r  r  r  r  r  r  r  r  r  rF   r  rK   r!   r   <module>r     sV    T T 9 9 4 N ,  
      	        )  + +4 8 + 	=4f <!! <B%8$$ %d', d'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E8$$ EN(** N(b/(## /d zMMO cF  Ls   6I I&%I&