
    Vhc                     H    d Z ddlZddlZddlmZmZmZmZ ddlm	Z	 da
	 d Zy)ab  Signal handling for multiprocessing data loading.

NOTE [ Signal handling in multiprocessing data loading ]

In cases like DataLoader, if a worker process dies due to bus error/segfault
or just hang, the main process will hang waiting for data. This is difficult
to avoid on PyTorch side as it can be caused by limited shm, or other
libraries users call in the workers. In this file and `DataLoader.cpp`, we make
our best effort to provide some error message to users when such unfortunate
events happen.

When a _BaseDataLoaderIter starts worker processes, their pids are registered in a
defined in `DataLoader.cpp`: id(_BaseDataLoaderIter) => Collection[ Worker pids ]
via `_set_worker_pids`.

When an error happens in a worker process, the main process received a SIGCHLD,
and Python will eventually call the handler registered below
(in `_set_SIGCHLD_handler`). In the handler, the `_error_if_any_worker_fails`
call checks all registered worker pids and raise proper error message to
prevent main process from hanging waiting for data from worker.

Additionally, at the beginning of each worker's `_utils.worker._worker_loop`,
`_set_worker_signal_handlers` is called to register critical signal handlers
(e.g., for SIGSEGV, SIGBUS, SIGFPE, SIGTERM) in C, which just prints an error
message to stderr before triggering the default handler. So a message will also
be printed from the worker process when it is killed by such signals.

See NOTE [ Data Loader Multiprocessing Shutdown Logic ] for the reasoning of
this signal handling design and other mechanism we implement to make our
multiprocessing data loading robust to errors.
    N)_error_if_any_worker_fails_remove_worker_pids_set_worker_pids_set_worker_signal_handlers   )
IS_WINDOWSFc                  2   t         ry t        t        j                         t        j                        sy t
        ry t        j                  t        j                        t              sd fd} t        j                  t        j                  |        day )Nc                 L    t                t              sJ  | |       y y )N)r   callable)signumframeprevious_handlers     W/home/dcms/DCMS/lib/python3.12/site-packages/torch/utils/data/_utils/signal_handling.pyhandlerz%_set_SIGCHLD_handler.<locals>.handlerF   s/     	#$',---VU+ (    T)
r   
isinstance	threadingcurrent_thread_MainThread_SIGCHLD_handler_setsignal	getsignalSIGCHLDr   )r   r   s    @r   _set_SIGCHLD_handlerr   6   sp    i..0)2G2GH''7$%  , MM&..'*r   )__doc__r   r   torch._Cr   r   r   r    r   r   r    r   r   <module>r      s4   @      = r   