o
    >h*                     @  s   d Z ddlmZ ddlmZmZ ddlmZmZm	Z	m
Z
mZ ddlmZmZmZ ddlmZ ddlmZmZ ddlmZ dd	lmZ dd
lmZ edZedZG dd deZG dd deZe  Z!G dd dZ"dS )z
twisted.python.threadpool: a pool of threads to which we dispatch tasks.

In most cases you can just use C{reactor.callInThread} and friends
instead of creating a thread pool directly.
    )annotations)Threadcurrent_thread)AnyCallableListOptionalTypeVar)	ParamSpecProtocol	TypedDict)pool)contextlog)
deprecated)Failure)Version_P_Rc                   @  s   e Zd ZdddZdS )_SupportsQsizereturnintc                 C  s   d S N selfr   r   y/var/www/vedio/testing/chatpythonscript.ninositsolution.com/env/lib/python3.10/site-packages/twisted/python/threadpool.pyqsize   s   z_SupportsQsize.qsizeNr   r   __name__
__module____qualname__r   r   r   r   r   r      s    r   c                   @  s   e Zd ZU ded< ded< dS )_Stater   minmaxN)r    r!   r"   __annotations__r   r   r   r   r#   "   s   
 r#   c                   @  s
  e Zd ZdZdZdZdZdZdZe	Z
eeedddd	d
deZeeZ	dBdCddZedDddZedEddZedEddZedFddZeZdGdd ZdGd!d"ZdHd$d%ZdGd&d'ZdId*d+ZdJd,d-ZdKd4d5ZdLd9d:ZdGd;d<Z 	dMdNd>d?Z!dGd@dAZ"dS )O
ThreadPoola  
    This class (hopefully) generalizes the functionality of a pool of threads
    to which work can be dispatched.

    L{callInThread} and L{stop} should only be called from a single thread.

    @ivar started: Whether or not the thread pool is currently running.
    @type started: L{bool}

    @ivar threads: List of workers currently running in this thread pool.
    @type threads: L{list}

    @ivar _pool: A hook for testing.
    @type _pool: callable compatible with L{_pool}
          FNTwisted      r   zthreading.current_thread)versionreplacement
minthreadsr   
maxthreadsnameOptional[str]c                   sf   |dksJ d||ksJ d| _ | _| _g  _d fd	d
}d fdd} || _dS )ac  
        Create a new threadpool.

        @param minthreads: minimum number of threads in the pool
        @type minthreads: L{int}

        @param maxthreads: maximum number of threads in the pool
        @type maxthreads: L{int}

        @param name: The name to give this threadpool; visible in log messages.
        @type name: native L{str}
        r   minimum is negativeminimum is greater than maximumar   kwr   r   c                    s(    j | d  i|} j| |S )Nr1   )threadFactory_generateNamethreadsappend)r5   r6   threadr   r   r   trackingThreadFactory`   s   z2ThreadPool.__init__.<locals>.trackingThreadFactoryr   c                     s    j sdS  jS )Nr   )startedr%   r   r   r   r   currentLimitg   s   z)ThreadPool.__init__.<locals>.currentLimitN)r5   r   r6   r   r   r   r   )r$   r%   r1   r9   _pool_team)r   r/   r0   r1   r<   r>   r   r   r   __init__J   s   zThreadPool.__init__r   c                 C  s   | j  }|j|j S )a  
        For legacy compatibility purposes, return a total number of workers.

        @return: the current number of workers, both idle and busy (but not
            those that have been quit by L{ThreadPool.adjustPoolsize})
        @rtype: L{int}
        )r@   
statisticsidleWorkerCountbusyWorkerCount)r   statsr   r   r   workersn   s   
	zThreadPool.workers
list[None]c                 C     dg| j  j S )z
        For legacy compatibility purposes, return the number of busy workers as
        expressed by a list the length of that number.

        @return: the number of workers currently processing a work item.
        @rtype: L{list} of L{None}
        N)r@   rB   rD   r   r   r   r   workingz   s   	zThreadPool.workingc                 C  rH   )a,  
        For legacy compatibility purposes, return the number of idle workers as
        expressed by a list the length of that number.

        @return: the number of workers currently alive (with an allocated
            thread) but waiting for new work.
        @rtype: L{list} of L{None}
        N)r@   rB   rC   r   r   r   r   waiters   s   
zThreadPool.waitersr   c                   s   G  fddd}| S )z
        For legacy compatibility purposes, return an object with a C{qsize}
        method that indicates the amount of work not yet allocated to a worker.

        @return: an object with a C{qsize} method.
        c                      s   e Zd Zd fddZdS )z$ThreadPool._queue.<locals>.NotAQueuer   r   c                   s    j  jS )a  
                Pretend to be a Python threading Queue and return the
                number of as-yet-unconsumed tasks.

                @return: the amount of backlogged work not yet dispatched to a
                    worker.
                @rtype: L{int}
                )r@   rB   backloggedWorkCount)qr   r   r   r      s   	z*ThreadPool._queue.<locals>.NotAQueue.qsizeNr   r   r   r   r   r   	NotAQueue   s    rM   r   )r   rM   r   r   r   _queue   s   	zThreadPool._queueNonec                 C  s8   d| _ d| _|   | j j}|r| j| dS dS )z'
        Start the threadpool.
        FTN)joinedr=   adjustPoolsizer@   rB   rK   grow)r   backlogr   r   r   start   s   zThreadPool.startc                 C     | j d dS )z
        Increase the number of available workers for the thread pool by 1, up
        to the maximum allowed by L{ThreadPool.max}.
        r,   N)r@   rR   r   r   r   r   startAWorker      zThreadPool.startAWorkerstrc                 C  s   d| j pt|  d| j S )z
        Generate a name for a new pool thread.

        @return: A distinctive name for the thread.
        @rtype: native L{str}
        zPoolThread--)r1   idrF   r   r   r   r   r8      s   zThreadPool._generateNamec                 C  rU   )zn
        Decrease the number of available workers by 1, by quitting one as soon
        as it's idle.
        r,   N)r@   shrinkr   r   r   r   stopAWorker   rW   zThreadPool.stopAWorkerstater#   c                 C  s"   t | d| t| | j| j d S )N__dict__)setattrr'   rA   r$   r%   )r   r]   r   r   r   __setstate__   s   zThreadPool.__setstate__c                 C  s   t | j| jdS )N)r$   r%   )r#   r$   r%   r   r   r   r   __getstate__   s   zThreadPool.__getstate__funcCallable[_P, object]args_P.argsr6   	_P.kwargsc                 O  s   | j d|g|R i | dS )a   
        Call a callable object in a separate thread.

        @param func: callable object to be called in separate thread

        @param args: positional arguments to be passed to C{func}

        @param kw: keyword args to be passed to C{func}
        N)callInThreadWithCallback)r   rb   rd   r6   r   r   r   callInThread   s   zThreadPool.callInThreadonResult&Optional[Callable[[bool, _R], object]]Callable[_P, _R]c                   sR   | j rdS tj jd d	fdd fdd_|_| j dS )
a$  
        Call a callable object in a separate thread and call C{onResult} with
        the return value, or a L{twisted.python.failure.Failure} if the
        callable raises an exception.

        The callable is allowed to block, but the C{onResult} function must not
        block and should perform as little work as possible.

        A typical action for C{onResult} for a threadpool used with a Twisted
        reactor would be to schedule a L{twisted.internet.defer.Deferred} to
        fire in the main reactor thread using C{.callFromThread}.  Note that
        C{onResult} is called inside the separate thread, not inside the
        reactor thread.

        @param onResult: a callable with the signature C{(success, result)}.
            If the callable returns normally, C{onResult} is called with
            C{(True, result)} where C{result} is the return value of the
            callable.  If the callable throws an exception, C{onResult} is
            called with C{(False, failure)}.

            Optionally, C{onResult} may be L{None}, in which case it is not
            called at all.

        @param func: callable object to be called in separate thread

        @param args: positional arguments to be passed to C{func}

        @param kw: keyword arguments to be passed to C{func}
        Nr   rO   c                    sj   z   } d}W n ty   t } d}Y nw d  _  jd ur* ||  d  _d S |s3t|  d S d S )NTF)theWorkBaseExceptionr   ri   r   err)resultok)	inContextr   r   rr     s   

z6ThreadPool.callInThreadWithCallback.<locals>.inContextc                     s   t jg R i S r   )r   callr   )rd   ctxrb   r6   r   r   <lambda>  s    z5ThreadPool.callInThreadWithCallback.<locals>.<lambda>r   rO   )	rP   r   theContextTrackercurrentContextcontextsrm   ri   r@   do)r   ri   rb   rd   r6   r   )rd   rt   rb   rr   r6   r   rg      s   $z#ThreadPool.callInThreadWithCallbackc                 C  s.   d| _ d| _| j  | jD ]}|  qdS )z9
        Shutdown the threads in the threadpool.
        TFN)rP   r=   r@   quitr9   join)r   r;   r   r   r   stop$  s   


zThreadPool.stopOptional[int]c                 C  s   |du r| j }|du r| j}|dksJ d||ksJ d|| _ || _| js)dS | j| jkr9| j| j| j  | j| j k rK| j| j | j  dS dS )z
        Adjust the number of available threads by setting C{min} and C{max} to
        new values.

        @param minthreads: The new value for L{ThreadPool.min}.

        @param maxthreads: The new value for L{ThreadPool.max}.
        Nr   r3   r4   )r$   r%   r=   rF   r@   r[   rR   )r   r/   r0   r   r   r   rQ   .  s   zThreadPool.adjustPoolsizec                 C  s:   t d| j  t d| j  t d| j  dS )zw
        Dump some plain-text informational messages to the log about the state
        of this L{ThreadPool}.
        z	waiters: z	workers: ztotal: N)r   msgrJ   rI   r9   r   r   r   r   	dumpStatsM  s   zThreadPool.dumpStats)r(   r)   N)r/   r   r0   r   r1   r2   r   )r   rG   )r   r   rv   )r   rX   )r]   r#   r   rO   )r   r#   )rb   rc   rd   re   r6   rf   r   rO   )
ri   rj   rb   rk   rd   re   r6   rf   r   rO   )NN)r/   r~   r0   r~   r   rO   )#r    r!   r"   __doc__r$   r%   rP   r=   r1   r   r7   staticmethodr   r   r   currentThreadr?   rA   propertyrF   rI   rJ   rN   rL   rT   rV   r8   r\   r`   ra   rh   rg   r}   rQ   r   r   r   r   r   r'   *   sP    $




	




Ar'   N)#r   
__future__r   	threadingr   r   typingr   r   r   r   r	   typing_extensionsr
   r   r   twisted._threadsr   r?   twisted.pythonr   r   twisted.python.deprecater   twisted.python.failurer   twisted.python.versionsr   r   r   r   r#   object
WorkerStopr'   r   r   r   r   <module>   s    