Your IP : 216.73.216.213


Current Path : /opt/alt/python39/lib64/python3.9/test/__pycache__/
Upload File :
Current File : //opt/alt/python39/lib64/python3.9/test/__pycache__/test_threading.cpython-39.opt-1.pyc

a

XC?h+��@sVdZddlZddlmZmZmZmZddlmZm	Z	ddl
Z
ddlZddlZddl
Z
ddlZddlZddlZddlZddlZddlZddlZddlZddlmZddlmZdZGdd	�d	e�ZGd
d�de
j�ZGdd
�d
ej�ZGdd�de�ZGdd�de�Z Gdd�de�Z!Gdd�de�Z"Gdd�de
j�Z#Gdd�de�Z$Gdd�de�Z%Gdd�dej&�Z&Gdd�dej'�Z(e�)e
j*dud �Gd!d"�d"ej'��Z+Gd#d$�d$ej,�Z,Gd%d&�d&ej'�Z-Gd'd(�d(ej.�Z.Gd)d*�d*ej/�Z/Gd+d,�d,ej0�Z0Gd-d.�d.ej1�Z1Gd/d0�d0ej�Z2Gd1d2�d2ej�Z3Gd3d4�d4ej�Z4e5d5k�rRe�6�dS)6z!
Tests for the threading module.
�N)�verbose�
import_module�cpython_only�unlink)�assert_python_ok�assert_python_failure)�
lock_tests)�support)Znetbsd5zhp-ux11c@s,eZdZdd�Zdd�Zdd�Zdd�Zd	S)
�CountercCs
d|_dS)Nr��value��self�r�8/opt/alt/python39/lib64/python3.9/test/test_threading.py�__init__#szCounter.__init__cCs|jd7_dS�N�rr
rrr�inc%szCounter.inccCs|jd8_dSrrr
rrr�dec'szCounter.deccCs|jS�Nrr
rrr�get)szCounter.getN)�__name__�
__module__�__qualname__rrrrrrrrr
"sr
c@seZdZdd�Zdd�ZdS)�
TestThreadcCs,tjj||d�||_||_||_||_dS)N��name)�	threading�Threadr�testcase�sema�mutex�nrunning)rrr r!r"r#rrrr-s
zTestThread.__init__c	Cs&t��d}tr&td|j|df�|j��|j�B|j��trTt|j��d�|j	�
|j��d�Wd�n1s|0Yt�|�tr�td|jd�|j�J|j�
�|j	�|j��d�tr�td	|j|j��f�Wd�n1s�0YWd�n1�s0YdS)
Ng��@ztask %s will run for %.1f usecg��.Aztasks are running�Ztask�donerz$%s is finished. %d tasks are running)�randomr�printrr!r"r#rrr ZassertLessEqual�time�sleeprZassertGreaterEqual)rZdelayrrr�run4s*�
2

�zTestThread.runN)rrrrr*rrrrr,src@seZdZdd�Zdd�ZdS)�BaseTestCasecCstj��|_dSr)�testr	Zthreading_setup�_threadsr
rrr�setUpNszBaseTestCase.setUpcCstjj|j�tj��dSr)r,r	Zthreading_cleanupr-Z
reap_childrenr
rrr�tearDownQszBaseTestCase.tearDownN)rrrr.r/rrrrr+Msr+c@s�eZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Ze�eed�d �d!d"��Ze�eed�d#�d$d%��Ze�eed�d �d&d'��Zd(d)�Ze�eed�d*�e�eed+�d,�d-d.���Ze�ejevd/�e�eed�d*�e�eed+�d,�d0d1����Zd2d3�Z d4d5�Z!d6d7�Z"d8d9�Z#d:d;�Z$e%d<d=��Z&e%d>d?��Z'd@dA�Z(dBdC�Z)dDdE�Z*dFS)G�ThreadTestsc	Cs0d}tjdd�}t��}t�}g}t|�D]F}td|||||�}|�|�|�|j�|�	t
|�d�|��q*ttd�r�t
dd�|D��t��hB}|�d|�|�t|�|d	�tr�td
�|D]D}|��|�|���|�|jd�|�|j�|�	t
|�d�q�t�rtd
�|�|��d�dS)N�
r$rz<thread %d>z^<TestThread\(.*, initial\)>$�
get_native_idcss|]}|jVqdSr)Z	native_id)�.0�trrr�	<genexpr>n�z/ThreadTests.test_various_ops.<locals>.<genexpr>rz!waiting for all tasks to completerz#^<TestThread\(.*, stopped -?\d+\)>$zall tasks done)r�BoundedSemaphore�RLockr
�ranger�append�assertIsNone�ident�assertRegex�repr�start�hasattr�setr2�assertNotIn�assertEqual�lenrr'�join�assertFalse�is_alive�assertNotEqual�assertIsNotNoner)	rZNUMTASKSr!r"Z
numrunning�threads�ir4Z
native_idsrrr�test_various_opsZs4


zThreadTests.test_various_opscs�|�t��j���fdd�}t���g�t���4t�|d�}��	�|�
�d|�Wd�n1sl0Ytj�d=dS)Ncs��t��j����dSr)r:r�
currentThreadr<rAr�r%r<rr�f�sz9ThreadTests.test_ident_of_no_threading_threads.<locals>.frr)rIrrMr<�Eventr	�wait_threads_exit�_thread�start_new_thread�waitrC�_active)rrO�tidrrNr�"test_ident_of_no_threading_threads~s
.z.ThreadTests.test_ident_of_no_threading_threadscCsPtrtd�zt�d�Wntjy8t�d��Yn0|��t�d�dS)Nz!with 256 KiB thread stack size...i�4platform does not support changing thread stack sizer�	rr'r�
stack_sizerR�error�unittestZSkipTestrLr
rrr�test_various_ops_small_stack�s�
z(ThreadTests.test_various_ops_small_stackcCsPtrtd�zt�d�Wntjy8t�d��Yn0|��t�d�dS)Nzwith 1 MiB thread stack size...irXrrYr
rrr�test_various_ops_large_stack�s�
z(ThreadTests.test_various_ops_large_stackcCs�dd�}t��}|��t���&t�||f�}|��Wd�n1sL0Y|�|tj�|�	tj|tj
�|�tj|���|�
ttj|�d�tj|=dS)NcSst��|��dSr)r�current_thread�release)r"rrrrO�sz*ThreadTests.test_foreign_thread.<locals>.f�_DummyThread)r�Lock�acquirer	rQrRrS�assertInrU�assertIsInstancera�
assertTruerGr=r>)rrOr"rVrrr�test_foreign_thread�s
&zThreadTests.test_foreign_threadc	s�td�}|jj}|j|jf|_Gdd�dt��|���}t��}|�	|t
�|�|d�z|||�}qdWn�yzYn0|�d�z|�
|d�Wnty�Yn0t���t���G���fdd�dtj�}|�}d	|_|��tr�td
�t�rtd�|d|�}|�
|d�t�r&td
����}|�|�t�rFtd�|�|j�t�r`td�||j|�}|�
|d�t�r�td��jtjd�|�|j�t�r�td�|j�r�|��dS)N�ctypesc@seZdZdS)z<ThreadTests.test_PyThreadState_SetAsyncExc.<locals>.AsyncExcN)rrrrrrr�AsyncExc�srirzAsyncExc not raisedrcseZdZ���fdd�ZdS)z:ThreadTests.test_PyThreadState_SetAsyncExc.<locals>.WorkercsNt��|_d|_z���t�d�qWn �yHd|_���Yn0dS)NFg�������?T)r�	get_ident�id�finishedrAr(r)r
�riZworker_saw_exceptionZworker_startedrrr*�s
z>ThreadTests.test_PyThreadState_SetAsyncExc.<locals>.Worker.runN�rrrr*rrmrr�Worker�sroTz    started worker threadz     trying nonsensical thread id���z,    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�Ztimeoutz    all OK -- joining worker)rZ	pythonapiZPyThreadState_SetAsyncExcZc_ulongZ	py_object�argtypes�	Exceptionrrjre�intZ
assertGreaterZfailrC�UnboundLocalErrorrPr�daemonr?rr'rTrfrFrlrkr	�
SHORT_TIMEOUTrE)	rrhZ
set_async_excZ	exceptionrV�resultror4�retrrmr�test_PyThreadState_SetAsyncExc�sb





z*ThreadTests.test_PyThreadState_SetAsyncExccCs^dd�}tj}|t_z<tjdd�d�}|�tj|j�|�|tjvd�W|t_n|t_0dS)NcWst���dSr)r�ThreadError��argsrrr�fail_new_threadsz7ThreadTests.test_limbo_cleanup.<locals>.fail_new_threadcSsdSrrrrrr�<lambda>r6z0ThreadTests.test_limbo_cleanup.<locals>.<lambda>��targetz:Failed to cleanup _limbo map on failure of Thread.start().)r�_start_new_threadr�assertRaisesr{r?rFZ_limbo)rr~r�r4rrr�test_limbo_cleanups�zThreadTests.test_limbo_cleanupcCs(td�tdd�\}}}|�|d�dS)Nrh�-caNif 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)
            �*)rrrC�r�rc�out�errrrr�test_finalize_running_thread#sz(ThreadTests.test_finalize_running_threadcCstdd�dS)Nr�aPif 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)
            )rr
rrr�test_finalize_with_traceDsz$ThreadTests.test_finalize_with_tracecCs0tdd�\}}}|�|��d�|�|d�dS)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
            s5Woke up, sleep function is: <built-in function sleep>r6)rrC�stripr�rrr�test_join_nondaemon_on_shutdown]s

�z+ThreadTests.test_join_nondaemon_on_shutdownc	Cs�tj}t��}zhtdd�D]N}t�|d�tjdd�d�}|��|��|�}|�	||d||f�qWt�|�nt�|�0dS)Nr�dg-C��6*?cSsdSrrrrrrryr6z7ThreadTests.test_enumerate_after_join.<locals>.<lambda>r�z&#1703448 triggered after %d trials: %s)
r�	enumerate�sys�getswitchintervalr9�setswitchintervalrr?rErB)r�enum�old_intervalrKr4�lrrr�test_enumerate_after_joinqs
�z%ThreadTests.test_enumerate_after_joincCs�Gdd�dt�}|dd�}t�|�}|j��~|j|�dt�|��d�|dd�}t�|�}|j��~|j|�dt�|��d�dS)Nc@seZdZdd�Zdd�ZdS)zDThreadTests.test_no_refcycle_through_target.<locals>.RunSelfFunctioncSs.||_tj|j|fd|id�|_|j��dS)N�yet_another)r�r}�kwargs)�should_raiserr�_run�threadr?)rr�rrrr�s�zMThreadTests.test_no_refcycle_through_target.<locals>.RunSelfFunction.__init__cSs|jr
t�dSr)r��
SystemExit)rZ	other_refr�rrrr��szIThreadTests.test_no_refcycle_through_target.<locals>.RunSelfFunction._runN)rrrrr�rrrr�RunSelfFunction�s	r�F)r�z%d references still around)�msgT)�object�weakref�refr�rEr;r��getrefcount)rr�Z
cyclic_objectZweak_cyclic_objectZraising_cyclic_objectZweak_raising_cyclic_objectrrr�test_no_refcycle_through_target�s&



��



��z+ThreadTests.test_no_refcycle_through_targetcCsHt��}|��|�d�|��|�d�t��}|��t��dS)NTr)	rrZisDaemonZ	setDaemonZgetNameZsetNamerPZisSet�activeCount)rr4�errr�test_old_threading_api�s

z"ThreadTests.test_old_threading_apicCs2t��}|�dt|��d|_|�dt|��dS�NrvT)rrrBr>rvrd�rr4rrr�test_repr_daemon�szThreadTests.test_repr_daemoncCsHt��}|�|j�tjdd�}|�|j�tjdd�}|�|j�dS)NF�rvT)rrrFrvrfr�rrr�test_daemon_param�szThreadTests.test_daemon_param�fork�needs os.fork()cCs:t�d�}td|�\}}}|�|d�|�|��d�dS)Na�
            import atexit
            import os
            import sys
            from test.support import wait_process

            # Import the threading module to register its "at fork" callback
            import threading

            def exit_handler():
                pid = os.fork()
                if not pid:
                    print("child process ok", file=sys.stderr, flush=True)
                    # child process
                    sys.exit()
                else:
                    wait_process(pid, exitcode=0)

            # exit_handler() will be called after threading._shutdown()
            atexit.register(exit_handler)
        r�r6schild process ok)�textwrap�dedentrrC�rstrip�r�code�_r�r�rrr�test_fork_at_exit�s
zThreadTests.test_fork_at_exitztest needs fork()cCs0d}td|�\}}}|�|d�|�|d�dS)Na�if 1:
            import _thread, threading, os, time

            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()
            if os.fork() == 0:
                assert threading.active_count() == 1, threading.active_count()
                os._exit(0)
            else:
                os.wait()
        r�r6�rrCr�rrr�test_dummy_thread_after_fork�sz(ThreadTests.test_dummy_thread_after_forkcCs�t��}|�tj|�tj�d�td�D]Z}tjdd�d�}|�	�t
��}|dkrnt
�|�
�rfdnd�q*|��tj|dd	�q*dS)
Ng���ư>�cSsdSrrrrrrr�r6z6ThreadTests.test_is_alive_after_fork.<locals>.<lambda>r�r�r1�Zexitcode)r�r��
addCleanupr�r,r	r9rrr?�osr��_exitrGrE�wait_process)rr�rKr4�pidrrr�test_is_alive_after_fork�sz$ThreadTests.test_is_alive_after_forkcsht��}��|jd���|jt��j���|jt����fdd�}tj|d�}|��|�	�dS)NZ
MainThreadcs��t��jt��j�dSr)rHr�main_threadr<r_rr
rrrOs�z'ThreadTests.test_main_thread.<locals>.fr�)
rr�rCrr<r_rjrr?rE)r�mainrOZthrr
r�test_main_threadszThreadTests.test_main_threadztest needs os.fork()�waitpidztest needs os.waitpid()cCs@d}td|�\}}}|���dd�}|�|d�|�|d�dS)Na�if 1:
            import os, threading
            from test import support

            pid = os.fork()
            if pid == 0:
                main = threading.main_thread()
                print(main.name)
                print(main.ident == threading.current_thread().ident)
                print(main.ident == threading.get_ident())
            else:
                support.wait_process(pid, exitcode=0)
        r��
�r6zMainThread
True
True
�r�decode�replacerC�rr�r�r�r��datarrr�test_main_thread_after_forks

z'ThreadTests.test_main_thread_after_fork�due to known OS bugcCs@d}td|�\}}}|���dd�}|�|d�|�|d�dS)Na�if 1:
            import os, threading, sys
            from test import support

            def f():
                pid = os.fork()
                if pid == 0:
                    main = threading.main_thread()
                    print(main.name)
                    print(main.ident == threading.current_thread().ident)
                    print(main.ident == threading.get_ident())
                    # stdout is fully buffered because not a tty,
                    # we have to flush before exit.
                    sys.stdout.flush()
                else:
                    support.wait_process(pid, exitcode=0)

            th = threading.Thread(target=f)
            th.start()
            th.join()
        r�r�r�r6zThread-1
True
True
r�r�rrr�/test_main_thread_after_fork_from_nonmain_thread*s
z;ThreadTests.test_main_thread_after_fork_from_nonmain_threadcCsBd}td|�\}}}|��}|�|d�|�|��dgd�dS)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�r6zGC: True True True�)rr�rC�
splitlinesr�rrr� test_main_thread_during_shutdownHs
�z,ThreadTests.test_main_thread_during_shutdowncCs$d}td|�\}}}|�|d�dS)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�r6r��rr�r�r�r�rrr�test_finalization_shutdownesz&ThreadTests.test_finalization_shutdowncs�t���t�����������fdd�}tj|d�}|�|jd�|�����|�|�	��|j}|�
|jdd�d����|�|jtj
d�d�|�|�	��|��|�
|�	��|�|j�|��dS)Ncs������t�d�dS)N�{�G�z�?)r`rcr(r)r�Zfinish�startedrrrO�sz'ThreadTests.test_tstate_lock.<locals>.fr�rrqF)rR�
allocate_lockrcrr�assertIs�_tstate_lockr?rfrGrFr`r	rwr;rE)rrOr4�tstate_lockrr�r�test_tstate_lock�s&zThreadTests.test_tstate_lockcs�t���t�����������fdd�}tj|d�}|�����|�dt|�����d}t	d�D]}|t|�vr�q�t
�d�qn|�|t|��|��dS)Ncs������dSr)r`rcrr�rrrO�sz(ThreadTests.test_repr_stopped.<locals>.fr�r�Zstoppedi�r�)
rRr�rcrrr?rdr>r`r9r(r)rE)rrOr4ZLOOKING_FORrKrr�r�test_repr_stopped�s"zThreadTests.test_repr_stoppedcs�tdd�D]�}t�|���fdd�t|�D�}|D]}|��q2|D]}|��qD�fdd�t|�D�}|D]}|��ql|D]}|��q~|�t�j�q
dS)Nrr1csg|]}tj�jd��qS�r�)rrrc�r3r��Zbsrr�
<listcomp>�s�z;ThreadTests.test_BoundedSemaphore_limit.<locals>.<listcomp>csg|]}tj�jd��qSr�)rrr`r�r�rrr��s�)r9rr7r?rEr��
ValueErrorr`)r�limitrJr4rr�r�test_BoundedSemaphore_limit�s"

�


�

z'ThreadTests.test_BoundedSemaphore_limitc	s��fdd��dd����fdd��d�_t��}t���z>t���ddl}|���td�D]
}��q`Wt�|�nt�|�0dS)	Ncs�Srr)�frame�event�arg)�
noop_tracerrr��sz9ThreadTests.test_frame_tstate_tracing.<locals>.noop_tracecssdVqdS)N�	generatorrrrrrr��sz8ThreadTests.test_frame_tstate_tracing.<locals>.generatorcs�jdur���_t�j�Sr)�gen�nextr)�callbackr�rrr��s
z7ThreadTests.test_frame_tstate_tracing.<locals>.callbackrr$)r�r��gettrace�settracer�	_testcapiZcall_in_temporary_c_threadr9)rZ	old_tracer�r,r)r�r�r�r�test_frame_tstate_tracing�s



z%ThreadTests.test_frame_tstate_tracingc	Cs�dD]�}|j|d��vt��}tj|j|d�}|��|j}|sP|�|tj�n|�	|tj�|�
�|��|�	|tj�Wd�q1s�0YqdS)N)FTr�)r�rv)ZsubTestrrPrrTr?r�rdZ_shutdown_locksrBrArE)rrvr�r�r�rrr�test_shutdown_locksszThreadTests.test_shutdown_lockscCs$tdd�\}}}|�|��d�dS)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()
        sthread_dict.atexit = 'value')rrCr�r�rrr�test_locals_at_exitszThreadTests.test_locals_at_exitcCsDdd�}t��� tj|d���Wd�n1s60YdS)NcSsdSrrrrrr�noop,r6z0ThreadTests.test_leak_without_join.<locals>.noopr�)r	rQrrr?)rr�rrr�test_leak_without_join)s
z"ThreadTests.test_leak_without_joincCs6t�d�}td|�\}}}|�|d�|�|d�dS)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�r6)r�r�rrCr�rrr�test_import_from_another_thread1s
z+ThreadTests.test_import_from_another_threadN)+rrrrLrWr]r^rgrzr�r�r�r�r�r�r�r�r�r\�
skipUnlessr@r�r�r�r�r�r��skipIfr��platform�platforms_to_skipr�r�r�r�r�r�rr�r�r�r�r�rrrrr0VsR$X!



##
'
r0c@s�eZdZdd�Zdd�Ze�eed�d�e�	e
jevd�dd	���Z
e�eed�d�e�	e
jevd�d
d���Ze�	e
jevd�dd
��Ze�eed�d�e�	e
jevd�dd���Ze�eed�d�dd��ZdS)�ThreadJoinOnShutdowncCs8d|}td|�\}}}|���dd�}|�|d�dS)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�zend of main
end of thread
r�)r�scriptr�r�r�r�rrr�
_run_and_joinUs
�z"ThreadJoinOnShutdown._run_and_joincCsd}|�|�dS)Nz�if 1:
            import os
            t = threading.Thread(target=joiningfunc,
                                 args=(threading.current_thread(),))
            t.start()
            time.sleep(0.1)
            print('end of main')
            �r��rr�rrr�test_1_join_on_shutdownfsz,ThreadJoinOnShutdown.test_1_join_on_shutdownr�r�r�cCsd}|�|�dS)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')
            r�r�rrr�test_2_join_in_forked_processrsz2ThreadJoinOnShutdown.test_2_join_in_forked_processcCsd}|�|�dS)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()
            r�r�rrr�!test_3_join_in_forked_from_thread�sz6ThreadJoinOnShutdown.test_3_join_in_forked_from_threadcCs"d}td|�\}}}|�|�dS)Nacif 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.'''
                while True:
                    with open(os.__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��rrF�rr�r�r�r�rrr�test_4_daemon_threads�s!z*ThreadJoinOnShutdown.test_4_daemon_threadscCsNdd�}g}td�D]"}tj|d�}|�|�|��q|D]}|��q<dS)NcSs.t��}|dkr tj|dd�n
t�d�dS)Nr�2r�)r�r�r	r�r�)r�rrr�do_fork_and_wait�szIThreadJoinOnShutdown.test_reinit_tls_after_fork.<locals>.do_fork_and_wait�r�)r9rrr:r?rE)rrrJrKr4rrr�test_reinit_tls_after_fork�s	

z/ThreadJoinOnShutdown.test_reinit_tls_after_forkcCs�g}td�D]&}tjdd�d�}|�|�|��qt��}|dkrltt�	��dkr`t�
d�qzt�
d�ntj|dd	�|D]}|�
�q~dS)
NrcSs
t�d�S)Ng333333�?)r(r)rrrrr�r6zKThreadJoinOnShutdown.test_clear_threads_states_after_fork.<locals>.<lambda>r�rr�3�4r�)r9rrr:r?r�r�rDr��_current_framesr�r	r�rE)rrJrKr4r�rrr�$test_clear_threads_states_after_fork�s

z9ThreadJoinOnShutdown.test_clear_threads_states_after_forkN)rrrr�r�r\r�r@r�r�r�r�r�r�rrrrrrrrr�Ss
(r�c@s0eZdZdd�Zdd�Zdd�Zedd��Zd	S)
�SubinterpThreadingTestscCsFt��\}}|�tj|�|�tj|�ttd�r>t�|d�||fS)N�set_blockingF)r��piper��closer@r
)r�r�wrrrr�s
zSubinterpThreadingTests.pipecCsL|��\}}t�d|f�}tj�|�}|�|d�|�t�|d�d�dS)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()
        rr�x�	rr�r�r,r	Zrun_in_subinterprCr��read�rrrr�ryrrr�test_threads_joins�z)SubinterpThreadingTests.test_threads_joincCsL|��\}}t�d|f�}tj�|�}|�|d�|�t�|d�d�dS)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()
        rrrrrrrr�test_threads_join_2#s�z+SubinterpThreadingTests.test_threads_join_2cCshdtjj�d�}d|f}tj��� td|�\}}}Wd�n1sJ0Y|�d|���dS)Nz�if 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()
            z[if 1:
            import _testcapi

            _testcapi.run_in_subinterp(%r)
            r�z:Fatal Python error: Py_EndInterpreter: not the last thread)r,r	rwZSuppressCrashReportrrdr�)rZsubinterp_coder�r�r�r�rrr�test_daemon_threads_fatal_errorHs��.�z7SubinterpThreadingTests.test_daemon_threads_fatal_errorN)rrrrrrrrrrrrr�s
%rc@sdeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�Zdd�Zdd�Z
dS)�ThreadingExceptionTestscCs*t��}|��|�t|j�|��dSr)rrr?r��RuntimeErrorrE�rr�rrr�test_start_thread_againcsz/ThreadingExceptionTests.test_start_thread_againcCst��}|�t|j�dSr)rr_r�rrE)rr_rrr�test_joining_current_threadisz3ThreadingExceptionTests.test_joining_current_threadcCst��}|�t|j�dSr)rrr�rrErrrr�test_joining_inactive_threadmsz4ThreadingExceptionTests.test_joining_inactive_threadcCs.t��}|��|�tt|dd�|��dSr�)rrr?r�r�setattrrErrrr�test_daemonize_active_threadqsz4ThreadingExceptionTests.test_daemonize_active_threadcCst��}|�t|j�dSr)rrbr�rr`)r�lockrrr�test_releasing_unacquired_lockwsz6ThreadingExceptionTests.test_releasing_unacquired_lockcCshd}d}tjtjd|gtjtjd�}|��\}}|���dd�}|�|j	dd|���|�||�dS)	Naif 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')
            zend of main thread
r�)�stdout�stderrr�r�rzUnexpected error: )
�
subprocess�Popenr��
executable�PIPEZcommunicater�r�rC�
returncode)rr�Zexpected_output�pr#r$r�rrr�test_recursion_limit{s�z,ThreadingExceptionTests.test_recursion_limitcCs\d}td|�\}}}|�|d�|��}|�d|�|�d|�|�d|�|�d|�dS)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�r6�Exception in thread�"Traceback (most recent call last):�ZeroDivisionError�Unhandled exception�rrCr�rdrBrrrr�test_print_exception�sz,ThreadingExceptionTests.test_print_exceptioncCs\d}td|�\}}}|�|d�|��}|�d|�|�d|�|�d|�|�d|�dS)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�r6r,r-r.r/r0rrrr�%test_print_exception_stderr_is_none_1�sz=ThreadingExceptionTests.test_print_exception_stderr_is_none_1cCs4d}td|�\}}}|�|d�|�d|���dS)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�r6r/)rrCrBr�rrrr�%test_print_exception_stderr_is_none_2�sz=ThreadingExceptionTests.test_print_exception_stderr_is_none_2csXdd��G�fdd�dtj�}|�}|��|��|�|j�|�|jt�d|_dS)NcSs�dSrrrrrr�
bare_raise�szOThreadingExceptionTests.test_bare_raise_in_brand_new_thread.<locals>.bare_raisecseZdZdZ�fdd�ZdS)zOThreadingExceptionTests.test_bare_raise_in_brand_new_thread.<locals>.Issue27558Nc
s:z
��Wn*ty4}z||_WYd}~n
d}~00dSr)rs�exc)rr5�r4rrr*�s
zSThreadingExceptionTests.test_bare_raise_in_brand_new_thread.<locals>.Issue27558.run)rrrr5r*rr6rr�
Issue27558�sr7)rrr?rErIr5rer)rr7r�rr6r�#test_bare_raise_in_brand_new_thread�s	z;ThreadingExceptionTests.test_bare_raise_in_brand_new_threadcsLdd��|�ttjj��fdd�td�D�}|D]}|��|��q2dS)NcSsHttjjddd��"}|�d�t��Wd�n1s:0YdS)Nrzutf-8)�encoding� )�openr,r	�TESTFN�write�	traceback�format_stack)�fprrr�modify_files
zQThreadingExceptionTests.test_multithread_modify_file_noerror.<locals>.modify_filecsg|]}tj�d��qSr�)rr)r3rK�rArrr�s�zPThreadingExceptionTests.test_multithread_modify_file_noerror.<locals>.<listcomp>r�)r�rr,r	r<r9r?rE)rrJr4rrBr�$test_multithread_modify_file_noerrors
�z<ThreadingExceptionTests.test_multithread_modify_file_noerrorN)rrrrrrr r"r+r1r2r3r8rCrrrrr`src@seZdZdd�ZdS)�
ThreadRunFailcCstd��dS)N�
run failed�r�r
rrrr*szThreadRunFail.runNrnrrrrrDsrDc@s:eZdZdd�Zejdd��Zdd�Zdd�Zd	d
�Z	dS)�ExceptHookTestscCs�t�d��*}tdd�}|��|��Wd�n1s:0Y|����}|�d|j�d�|�|�d|�|�d|�|�d|�dS)	Nr$zexcepthook threadr�Exception in thread �:
�#Traceback (most recent call last):
z   raise ValueError("run failed")zValueError: run failed)	r	�captured_outputrDr?rE�getvaluer�rdr)rr$r�rrr�test_excepthooks
&zExceptHookTests.test_excepthookcCs�t�d��r}ztd��WnTtyl}z<t�gt���d��}zt�|�Wd}nd}0WYd}~n
d}~00Wd�n1s�0Y|�	��
�}|�dt���d�|�|�d|�|�d|�|�d|�dS)Nr$ZbugrHrIrJz  raise ValueError("bug")zValueError: bug)
r	rKr�rsrZExceptHookArgsr��exc_info�
excepthookrLr�rdrj)rr$r5r}rrr�test_excepthook_thread_None#s@z+ExceptHookTests.test_excepthook_thread_NonecCsfGdd�dtj�}t�d��&}|�}|��|��Wd�n1sH0Y|�|��d�dS)Nc@seZdZdd�ZdS)z4ExceptHookTests.test_system_exit.<locals>.ThreadExitcSst�d�dSr)r��exitr
rrrr*:sz8ExceptHookTests.test_system_exit.<locals>.ThreadExit.runNrnrrrr�
ThreadExit9srRr$r�)rrr	rKr?rErCrL)rrRr$r�rrr�test_system_exit8s&z ExceptHookTests.test_system_exitcs�d��fdd�}z�t�td|��&t�}|��|��Wd�n1sL0Y|��jt�|�t	�j
�d�|��j�j
j�|�
�j|�Wd�nd�0dS)Ncs|�dSrr)Z	hook_argsr|rr�hookHsz4ExceptHookTests.test_custom_excepthook.<locals>.hookrOrE)r	�	swap_attrrrDr?rErC�exc_typer��str�	exc_value�
exc_traceback�
__traceback__r�r�)rrTr�rr|r�test_custom_excepthookEs&z&ExceptHookTests.test_custom_excepthookc
s�dd�}d��fdd�}t�td|��~t�td|��Pt�d��&}t�}|��|��Wd�n1sn0YWd�n1s�0YWd�n1s�0Y|�|�	�d�|��d�dS)	NcSstd��dS)N�threading_hook failedrFr|rrr�threading_hook[szCExceptHookTests.test_custom_excepthook_fail.<locals>.threading_hookcst|��dSr)rW)rVrXrY�Zerr_strrr�sys_hook`sz=ExceptHookTests.test_custom_excepthook_fail.<locals>.sys_hookrOr$z#Exception in threading.excepthook:
r\)
r	rUrr�rKrDr?rErCrL)rr]r_r$r�rr^r�test_custom_excepthook_failZs ��b
�z+ExceptHookTests.test_custom_excepthook_failN)
rrrrMr	rrPrSr[r`rrrrrGs

rGc@s$eZdZdd�Zdd�Zdd�ZdS)�
TimerTestscCst�|�g|_t��|_dSr)r+r.�
callback_argsrrP�callback_eventr
rrrr.rs
zTimerTests.setUpcCs�t�d|j�}|��|j��|j�d�d|jd<|j�	�t�d|j�}|��|j��|�
t|j�d�|�
|jdifdifg�|�
�|�
�dS)Nr�ZblahZbarZfoor�r)rZTimer�
_callback_spyr?rcrTr}r:r��clearrCrDrbrE)rZtimer1Ztimer2rrr� test_init_immutable_default_argsws



z+TimerTests.test_init_immutable_default_argscOs*|j�|dd�|��f�|j��dSr)rbr:�copyrcrA)rr}r�rrrrd�szTimerTests._callback_spyN)rrrr.rfrdrrrrrapsrac@seZdZeej�ZdS)�	LockTestsN)rrr�staticmethodrrb�locktyperrrrrh�srhc@seZdZeej�ZdS)�PyRLockTestsN)rrrrirZ_PyRLockrjrrrrrk�srkzRLock not implemented in Cc@seZdZeej�ZdS)�CRLockTestsN)rrrrir�_CRLockrjrrrrrl�srlc@seZdZeej�ZdS)�
EventTestsN)rrrrirrPZ	eventtyperrrrrn�srnc@seZdZeej�ZdS)�ConditionAsRLockTestsN)rrrrir�	Conditionrjrrrrro�sroc@seZdZeej�ZdS)�ConditionTestsN)rrrrirrpZcondtyperrrrrq�srqc@seZdZeej�ZdS)�SemaphoreTestsN)rrrrirZ	Semaphore�semtyperrrrrr�srrc@seZdZeej�ZdS)�BoundedSemaphoreTestsN)rrrrirr7rsrrrrrt�srtc@seZdZeej�ZdS)�BarrierTestsN)rrrrirZBarrierZbarriertyperrrrru�sruc@seZdZdd�ZdS)�MiscTestCasecCs&dh}ddh}tj|td||d�dS)Nr{rMr�)rrR)�extra�	blacklist)r	Zcheck__all__r)rrwrxrrr�test__all__�s

�zMiscTestCase.test__all__N)rrrryrrrrrv�srvc@s$eZdZdd�Zdd�Zdd�ZdS)�InterruptMainTestscCsZdd�}tj|d�}|�t�� |��|��Wd�n1sD0Y|��dS)NcSst��dSr)rR�interrupt_mainrrrr�call_interrupt�szHInterruptMainTests.test_interrupt_main_subthread.<locals>.call_interruptr�)rrr��KeyboardInterruptr?rE)rr|r4rrr�test_interrupt_main_subthread�s&z0InterruptMainTests.test_interrupt_main_subthreadcCs6|�t��t��Wd�n1s(0YdSr)r�r}rRr{r
rrr�test_interrupt_main_mainthread�sz1InterruptMainTests.test_interrupt_main_mainthreadc
Csdt�tj�}zBt�tjtj�t��t�tjtj�t��Wt�tj|�nt�tj|�0dSr)�signal�	getsignal�SIGINT�SIG_IGNrRr{�SIG_DFL)rZhandlerrrr�test_interrupt_main_noerror�s
z.InterruptMainTests.test_interrupt_main_noerrorN)rrrr~rr�rrrrrz�srzc@s$eZdZdd�Zdd�Zdd�ZdS)�AtexitTestscCs.tdd�\}}}|�|�|�|��d�dS)Nr�z�if True:
            import threading

            def run_last():
                print('parrot')

            threading._register_atexit(run_last)
        sparrot)rrFrCr�r�rrr�test_atexit_output�s	
zAtexitTests.test_atexit_outputcCstdd�\}}}|�|�dS)Nr�aNif 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()
        rr�rrr�test_atexit_called_once�sz#AtexitTests.test_atexit_called_oncecCs.tdd�\}}}|�|�|�d|���dS)Nr�z�if 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)rrfrdr�r�rrr�test_atexit_after_shutdown�s

�z&AtexitTests.test_atexit_after_shutdownN)rrrr�r�r�rrrrr��s
r��__main__)7�__doc__Ztest.supportr,rrrrZtest.support.script_helperrrr&r�rRrr(r\r�r�r%r�r�r>rr	r�r�r
rrZTestCaser+r0r�rrrDrGrarhZ
RLockTestsrkr�rmrlrnrorqrrrtrurvrzr�rr�rrrr�<module>sf
!	,b2Z 2