K i: UdZddlZddlmZddlmZddlm Z ddl m Z m Z mZmZmZmZmZddlmZmZddlmZmZGd d eZGd d eZed edgiddZeed<d%deeddfdZd&deddfdZ d%deedeeeeefffdZ! d'dedeedeeddfdZ"de de fde deeeefffdZ#deeeeffdZ$deeeeffdZ%d(d e&de'fd!Z(d)d"e d#e ddfd$Z)y)*z0.0.12N)wraps)exit)_exit)AnyCallableDictListOptional TypedDictUnion)Thread Semaphore)Process cpu_countcVeZdZUdZeeed<eee ee fed<e ed<e ed<y) 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. poolenginenamethreadsN) __name__ __module__ __qualname____doc__r r__annotations__r typer rstrint[/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/multitasking/__init__.pyrr$s6 9  $v,W - .. I Lr rcreZdZUdZeed<eed<eed<eed<ee e e fed<e ee fed<eed<y ) 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_CORESENGINE MAX_THREADS KILL_RECEIVEDTASKSPOOLS POOL_NAMEN)rrrrrrrboolr r r rrrrr r!r#r#1sG N K fgo& '' Z  Nr r#threadFMain)r$r%r&r'r(r)r*configrreturnc>| |td<yttd<y)aConfigure 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)rs r!set_max_threadsr1Ns" '}!* }r kindcNd|jvr dtd<ydtd<y)aConfigure 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.)r2s r! set_enginer6ds(DJJL $x$xr rc| td}d}tdtddtk(rd}||tdtdddS)aRetrieve 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 r*r,r)rr4r)rrr)r.r)rrs r!getPoolr8{sb  |k"F gvk*+H5@'?6+#67 B r rcT|td< | t|ntd}|dkrd}||ntd}|td<|td<|dkDr t |ndd|j vrt nt||dtd td<y#ttf$r td}YwxYw) aCreate 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&rr%r4)rrrrr))r.r ValueError TypeErrorrr5rr )rrrs r! createPoolr=s,F;(#/CL & {)Vvh/?F$F=F8 '.k '"t&&,,.8'f ,F7OF;'(!  "('(sB B'&B'callee.c tds tdtdtdtffd tdtdtdtt t tfffd }|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)argskwargsr/ctdtdd}||5|i|cdddS|i|S#1swYyxYw)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*rNr.)r@rArr>s r! _run_via_poolztask.._run_via_pools_gvk23F;   /t.v. / /4*6* *  / /s6?c*tdtdddk(r |i|ytdsM tdtdd}|||d }td j||j|Sy#t$r|| }YAwxYw) 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*rrNr'rF)targetr@rAdaemon)rFr@rAr()r. Exceptionappendstart)r@rA engine_classsinglerDr>s r! async_methodztask..async_methods '?6+. / :a ? D #F #o& %gvk/BCHM &(!  7O " "6 * LLNM% %(! s"A;;BB)r.r=rrr r r r)r>rMrDs` @r!taskrNsr0 '? +S+C+C+  6]//!/ %( )//b r ctdS)aRetrieve 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(rCrr r!get_list_of_tasksrP3s '?r c\tdDcgc]}|js|c}Scc}w)aRetrieve 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") r()r.is_alive)rNs r!get_active_tasksrSCs$$G_ @T D @@ @s))sleepcdtd<tdtdddk(ry tdDcgc]}||jr|}}|D]}|jdttdDcgc]}||jr|c}}|dk(rn|dkDrt j | d td<ycc}wcc}w#t $rYwxYw) aWBlock 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*rrr(F)r.rRjoinlen_timerTrH)rTrN running_tasks still_runnings r!wait_for_tasksr\Ts&#F?gvk*+I6!; "(# M&  !   !'!# !M !qy E"1($F? =!    s. CC *C6C (C C CCselfclsctdtd< tddtd<y#t$rtdY wxYw)aEmergency 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'rFN)r.sysexit SystemExitosexit)r]r^s r!killallrcs>*#F? $F? q s 77)N))mainNN)r)NN)* __version__timerY functoolsrsysrr`osrrbtypingrrrr r r r threadingr rmultiprocessingrrrr#r.rrr1rr6r8r=rNrPrSfloatr+r\rcrr r!ros,h HHH(.   Y &;  ,Xc],d,,$S$$$.(3-4U38_0D+EB! 5 5 c]5 SM5 5p] S#X ] c8E&'/2334]@ 4fgo 67  A$uVW_56A";%;;|$#$3$$$r