
    h:              	       \   U d Z ddlZddlmZ ddlmZ ddlm	Z
 ddlmZmZmZmZmZmZmZ ddlmZmZ ddlmZmZ  G d	 d
e          Z G d de          Z e            d e            dg i ddZeed<   d'dee         ddfdZd(deddfdZ d'dee         deeeeef         f         fdZ!	 	 	 d)dedee         dee         ddfdZ"dedef         dedeeeef                  f         fdZ#deeeef                  fd Z$deeeef                  fd!Z%d*d"e&de'fd#Z(d+d$ed%eddfd&Z)dS ),z0.0.12    N)wraps)exit)_exit)AnyCallableDictListOptional	TypedDictUnion)Thread	Semaphore)Process	cpu_countc                   p    e Zd ZU dZee         ed<   eee	         ee
         f         ed<   eed<   eed<   dS )
PoolConfigzType definition for execution pool configuration.

    This defines the structure of each pool in the POOLS dictionary,
    containing the semaphore for limiting concurrent tasks, the engine
    type (Thread or Process), pool name, and thread count.
    poolenginenamethreadsN)__name__
__module____qualname____doc__r
   r   __annotations__r   typer   r   strint     S/var/www/html/marketdash/venv/lib/python3.11/site-packages/multitasking/__init__.pyr   r   $   s]           9
$v,W-....
IIILLLLLr    r   c                       e Zd ZU dZeed<   eed<   eed<   eed<   ee	e
ef                  ed<   eeef         ed<   eed<   d	S )
ConfigzType definition for global multitasking configuration.

    This structure holds all global state including CPU info, engine
    preferences, task tracking, and pool management. It serves as the
    central configuration store for the entire library.
    	CPU_CORESENGINEMAX_THREADSKILL_RECEIVEDTASKSPOOLS	POOL_NAMEN)r   r   r   r   r   r   r   boolr	   r   r   r   r   r   r   r    r!   r#   r#   1   s~           NNNKKKfgo&''''Z    NNNNNr    r#   threadFMain)r$   r%   r&   r'   r(   r)   r*   configr   returnc                 N    | | t           d<   dS t                      t           d<   dS )a  Configure the maximum number of concurrent threads/processes.

    This function allows users to override the default CPU-based thread
    count. Setting this affects new pools but not existing ones.

    Args:
        threads: Maximum concurrent tasks. If None, uses CPU count.
                 Must be positive integer or None.

    Example:
        set_max_threads(4)  # Limit to 4 concurrent tasks
        set_max_threads()   # Reset to CPU count
    Nr&   )r.   r   )r   s    r!   set_max_threadsr1   N   s0      '} !*}r     kindc                 ^    d|                                  v rdt          d<   dS dt          d<   dS )a  Configure the execution engine for new pools.

    This determines whether new tasks run in threads or separate
    processes. Threads share memory but processes are more isolated.
    Only affects pools created after this call.

    Args:
        kind: Engine type. Contains "process" for multiprocessing,
              anything else defaults to threading.

    Note:
        Threading: Faster startup, shared memory, GIL limitations
        Processing: Slower startup, isolated memory, true parallelism
    processr%   r,   N)lowerr.   )r3   s    r!   
set_enginer7   d   s9     DJJLL  $x $xr    r   c                     | t           d         } d}t           d         t           d                  d         t          k    rd}|| t           d         t           d                  d         dS )	a  Retrieve information about an execution pool.

    Returns a dictionary with pool metadata including engine type,
    name, and thread count. Useful for debugging and monitoring.

    Args:
        name: Pool name to query. If None, uses current active pool.

    Returns:
        Dictionary with keys: 'engine', 'name', 'threads'

    Raises:
        KeyError: If the specified pool doesn't exist
    Nr*   r,   r)   r   r5   r   )r   r   r   )r.   r   )r   r   s     r!   getPoolr9   {   sj      |k" Fgvk*+H5@@ '?6+#67	B  r    mainr   c                    | t           d<   	 |t          |          nt           d         }n$# t          t          f$ r t           d         }Y nw xY w|dk     rd}||nt           d         }|t           d<   |t           d<   |dk    rt	          |          ndd|                                v rt          nt          | |dt           d	         t           d         <   dS )
a  Create a new execution pool with specified configuration.

    Pools manage concurrent task execution using semaphores. Each pool
    has its own thread/process limit and engine type. Creating a pool
    automatically makes it the active pool for new tasks.

    Args:
        name: Unique identifier for this pool
        threads: Max concurrent tasks. None uses global MAX_THREADS.
                 Values < 2 create unlimited pools (no semaphore).
        engine: "process" or "thread". None uses global ENGINE setting.

    Note:
        Setting threads=0 or threads=1 creates an unlimited pool where
        all tasks run immediately without queuing.
    r*   Nr&      r   r%   r5   )r   r   r   r   r)   )r.   r   
ValueError	TypeErrorr   r6   r   r   )r   r   r   s      r!   
createPoolr?      s    , F;(#/CLLL& 	 	" ( ( ('(
 {{ )VVvh/?F $F=F8
 '.kk	'"""t&&,,..88''f, ,F7OF;'(((s   + AAcallee.c           
          t           d         st                       dt          dt          dt          f fdt                     dt          dt          dt          t
          t          t          f                  f fd            }|S )a\  Decorator that converts a function into an asynchronous task.

    This is the main decorator of the library. It wraps any function
    to make it run asynchronously in the background using the current
    pool's configuration (threads or processes).

    Args:
        callee: The function to be made asynchronous

    Returns:
        Decorated function that returns Thread/Process object or None

    Example:
        @task
        def my_function(x, y):
            return x + y

        result = my_function(1, 2)  # Returns Thread/Process object
        wait_for_tasks()  # Wait for completion
    r)   argskwargsr/   c                      t           d         t           d                  d         }|$|5   | i |cddd           S # 1 swxY w Y   dS  | i |S )a&  Internal wrapper that handles semaphore-controlled execution.

        This function is what actually runs in the background thread/process.
        It acquires the pool's semaphore (if any) before executing the
        original function, ensuring we don't exceed the concurrent limit.
        r)   r*   r   Nr.   )rB   rC   r   r@   s      r!   _run_via_poolztask.<locals>._run_via_pool   s     gvk23F; / /vt.v../ / / / / / / / / / / / / / / / / / 64*6***s   ?AAc                     t           d         t           d                  d         dk    r
 | i | dS t           d         s	 t           d         t           d                  d         } || |d	          }n# t          $ r  || |
          }Y nw xY wt           d                             |           |                                 |S dS )zThe actual decorated function that users call.

        This decides whether to run synchronously (for 0-thread pools)
        or asynchronously (for normal pools). It handles the creation
        and startup of Thread/Process objects.
        r)   r*   r   r   Nr'   r   F)targetrB   rC   daemon)rH   rB   rC   r(   )r.   	Exceptionappendstart)rB   rC   engine_classsinglerF   r@   s       r!   async_methodztask.<locals>.async_method   s    '?6+./	:a??FD#F###4 o& 	%gvk/BCHM &(! 	      %(!   7O""6*** LLNNN M ts   3A6 6BB)r.   r?   r   r   r
   r   r   r   )r@   rO   rF   s   ` @r!   taskrP      s    0 '? +S +C +C + + + + + +  6]]//!/	%(	)/ / / / / / ]/b r    c                      t           d         S )a  Retrieve all tasks ever created by this library.

    This includes both currently running tasks and completed ones.
    Useful for debugging and monitoring task history.

    Returns:
        List of all Thread/Process objects created by @task decorator

    Note:
        Completed tasks remain in this list until program termination.
        Use get_active_tasks() to see only currently running tasks.
    r(   rE   r   r    r!   get_list_of_tasksrR   3  s     '?r    c                  0    d t           d         D             S )a  Retrieve only the currently running tasks.

    Filters the complete task list to show only tasks that are still
    executing. This is more useful than get_list_of_tasks() for
    monitoring current system load.

    Returns:
        List of Thread/Process objects that are still running

    Example:
        active = get_active_tasks()
        print(f"Currently running {len(active)} tasks")
    c                 :    g | ]}|                                 |S r   is_alive.0rP   s     r!   
<listcomp>z$get_active_tasks.<locals>.<listcomp>Q  s%    @@@T@D@@@r    r(   rE   r   r    r!   get_active_tasksrZ   C  s     A@VG_@@@@r    sleepc                    dt           d<   t           d         t           d                  d         dk    rdS 	 	 d t           d         D             }|D ]}|                    d	           t          d
 t           d         D                       }|dk    rn| dk    rt          j        |            wn# t
          $ r Y nw xY wdt           d<   dS )aW  Block until all background tasks complete execution.

    This is the primary synchronization mechanism. It prevents new
    tasks from being created and waits for existing ones to finish.
    Essential for ensuring all work is done before program exit.

    Args:
        sleep: Seconds to sleep between checks. 0 means busy-wait.
               Higher values reduce CPU usage but increase latency.

    Returns:
        Always returns True when all tasks are complete

    Note:
        Sets KILL_RECEIVED=True during execution to prevent new tasks,
        then resets it to False when done.
    Tr'   r)   r*   r   r   c                 >    g | ]}||                                 |S NrU   rW   s     r!   rY   z"wait_for_tasks.<locals>.<listcomp>q  s5       ## ###r    r(      c                 >    g | ]}||                                 |S r^   rU   rW   s     r!   rY   z"wait_for_tasks.<locals>.<listcomp>|  s5     ! ! !## ###r    F)r.   joinlen_timer[   rJ   )r[   running_tasksrP   still_runnings       r!   wait_for_tasksrf   T  s   & #F? gvk*+I6!;;t	# !'  M &  		!   ! !!'! ! !  M !! qyyE"""1	#(     
 $F?4s   A8B/ /
B<;B<selfclsc                     dt           d<   	 t          d           n# t          $ r t          d           Y nw xY wdt           d<   dS )a  Emergency shutdown function that terminates the entire program.

    This is a last-resort function that immediately exits the program,
    potentially leaving tasks in an inconsistent state. It tries
    sys.exit() first, then os._exit() as a final measure.

    Args:
        self: Unused parameter kept for backward compatibility
        cls: Unused parameter kept for backward compatibility

    Warning:
        This function does NOT wait for tasks to complete cleanly.
        Use wait_for_tasks() for graceful shutdown instead.

    Note:
        The function attempts sys.exit(0) first (which allows cleanup
        handlers to run), falling back to os._exit(0) which terminates
        immediately without any cleanup.
    Tr'   r   FN)r.   sysexit
SystemExitosexit)rg   rh   s     r!   killallrm     s\    * #F?



   q					
 $F?s    88r^   )r2   )r:   NN)r   )NN)*__version__timerc   	functoolsr   sysr   rj   osr   rl   typingr   r   r   r	   r
   r   r   	threadingr   r   multiprocessingr   r   r   r#   r.   r   r   r1   r   r7   r9   r?   rP   rR   rZ   floatr+   rf   rm   r   r    r!   <module>rw      s2  , h                       H H H H H H H H H H H H H H H H H H ( ' ' ' ' ' ' ' . . . . . . . .
 
 
 
 
 
 
 
    Y   & 9;;    , ,Xc] ,d , , , ,,$ $S $$ $ $ $ $. (3- 4U38_0D+E    B ! 5 5
5c]5 SM5 
	5 5 5 5p]S#X]c8E&'/2334] ] ] ]@4fgo 67     A$uVW_56 A A A A"; ;% ; ; ; ; ;|$ $# $3 $$ $ $ $ $ $ $r    