a
    xd6                     @   s  d dl Z d dlZd dlZd dlZd dlmZ d dlZd dlZd dl	Z	d dl
mZ d dlZddlmZ ddlmZmZmZmZmZ ddlmZ e ZedZd	Ze Zd
d ZejddddG dd dZedddddZddddZ ddddZ!ddddZ"dS )    N)count)current_async_library_cvar   )CapacityLimiter)enable_ki_protectiondisable_ki_protectionRunVar	TrioTokenstart_thread_sooncoroutine_or_errorlimiter(   c                  C   s6   zt  } W n$ ty0   tt} t |  Y n0 | S )zGet the default `~trio.CapacityLimiter` used by
    `trio.to_thread.run_sync`.

    The most common reason to call this would be if you want to modify its
    :attr:`~trio.CapacityLimiter.total_tokens` attribute.

    )_limiter_localgetLookupErrorr   DEFAULT_LIMITset)r    r   E/var/www/html/Ranjet/env/lib/python3.9/site-packages/trio/_threads.pycurrent_default_thread_limiter$   s    r   TF)frozeneqhashc                   @   s   e Zd Ze ZdS )ThreadPlaceholderN)__name__
__module____qualname__attribnamer   r   r   r   r   8   s   r   )cancellabler   c          
         s   t j I dH  tdu r&t t j gdtt }t|fddt j	  fdd}t
 }t|j|}fdd}I dH  zt|| W n     Y n0 fd	d
}	t j|	I dH S )u  Convert a blocking operation into an async operation using a thread.

    These two lines are equivalent::

        sync_fn(*args)
        await trio.to_thread.run_sync(sync_fn, *args)

    except that if ``sync_fn`` takes a long time, then the first line will
    block the Trio loop while it runs, while the second line allows other Trio
    tasks to continue working while ``sync_fn`` runs. This is accomplished by
    pushing the call to ``sync_fn(*args)`` off into a worker thread.

    From inside the worker thread, you can get back into Trio using the
    functions in `trio.from_thread`.

    Args:
      sync_fn: An arbitrary synchronous callable.
      *args: Positional arguments to pass to sync_fn. If you need keyword
          arguments, use :func:`functools.partial`.
      cancellable (bool): Whether to allow cancellation of this operation. See
          discussion below.
      limiter (None, or CapacityLimiter-like object):
          An object used to limit the number of simultaneous threads. Most
          commonly this will be a `~trio.CapacityLimiter`, but it could be
          anything providing compatible
          :meth:`~trio.CapacityLimiter.acquire_on_behalf_of` and
          :meth:`~trio.CapacityLimiter.release_on_behalf_of` methods. This
          function will call ``acquire_on_behalf_of`` before starting the
          thread, and ``release_on_behalf_of`` after the thread has finished.

          If None (the default), uses the default `~trio.CapacityLimiter`, as
          returned by :func:`current_default_thread_limiter`.

    **Cancellation handling**: Cancellation is a tricky issue here, because
    neither Python nor the operating systems it runs on provide any general
    mechanism for cancelling an arbitrary synchronous function running in a
    thread. This function will always check for cancellation on entry, before
    starting the thread. But once the thread is running, there are two ways it
    can handle being cancelled:

    * If ``cancellable=False``, the function ignores the cancellation and
      keeps going, just like if we had called ``sync_fn`` synchronously. This
      is the default behavior.

    * If ``cancellable=True``, then this function immediately raises
      `~trio.Cancelled`. In this case **the thread keeps running in
      background** – we just abandon it to do whatever it's going to do, and
      silently discard any return value or errors that it raises. Only use
      this if you know that the operation is safe and side-effect free. (For
      example: :func:`trio.socket.getaddrinfo` uses a thread with
      ``cancellable=True``, because it doesn't really affect anything if a
      stray hostname lookup keeps running in the background.)

      The ``limiter`` is only released after the thread has *actually*
      finished – which in the case of cancellation may be some time after this
      function has returned. If :func:`trio.run` finishes before the thread
      does, then the limiter release method will never be called at all.

    .. warning::

       You should not use this function to call long-running CPU-bound
       functions! In addition to the usual GIL-related reasons why using
       threads for CPU-bound work is not very effective in Python, there is an
       additional problem: on CPython, `CPU-bound threads tend to "starve out"
       IO-bound threads <https://bugs.python.org/issue7946>`__, so using
       threads for CPU-bound work is likely to adversely affect the main
       thread running Trio. If you need to do this, you're better off using a
       worker process, or perhaps PyPy (which still has a GIL, but may do a
       better job of fairly allocating CPU time between threads).

    Returns:
      Whatever ``sync_fn(*args)`` returns.

    Raises:
      Exception: Whatever ``sync_fn(*args)`` raises.

    Nztrio.to_thread.run_sync-c                    s<    fdd}t | d d ur8tjd   d S )Nc                	      s&   z  W   S   0 d S N)unwraprelease_on_behalf_ofr   )r   placeholderresultr   r   do_release_then_return_result   s
    
z`to_thread_run_sync.<locals>.report_back_in_trio_thread_fn.<locals>.do_release_then_return_resultr   )outcomecapturetriolowlevelZ
reschedule)r&   r'   )r   r%   task_registerr&   r   report_back_in_trio_thread_fn   s    

z9to_thread_run_sync.<locals>.report_back_in_trio_thread_fnc                     sV   t d  t_z:  } t| rB|   tdt	d| W t`S t`0 d S NzBTrio expected a sync function, but {!r} appears to be asynchronousr   )
r   r   TOKEN_LOCALtokeninspectiscoroutineclose	TypeErrorformatgetattrret)argscurrent_trio_tokensync_fnr   r   	worker_fn   s    


z%to_thread_run_sync.<locals>.worker_fnc                    s*   z  |  W n tjy$   Y n0 d S r"   )run_sync_soonr*   RunFinishedErrorr-   )r;   r.   r   r   deliver_worker_fn_result   s    z4to_thread_run_sync.<locals>.deliver_worker_fn_resultc                    s$    rd d< t jjjS t jjjS d S )Nr   )r*   r+   ZAbortZ	SUCCEEDEDZFAILED)_)r!   r,   r   r   abort   s    
z!to_thread_run_sync.<locals>.abort)r*   r+   Zcheckpoint_if_cancelledboolr   current_tasknext_thread_counterr   r;   contextvarscopy_context	functoolspartialrunZacquire_on_behalf_ofr
   r$   Zwait_task_rescheduled)
r<   r!   r   r:   r    r=   contextZcontextvars_aware_worker_fnr@   rB   r   )r:   r!   r;   r   r%   r.   r<   r,   r   to_thread_run_sync=   s*    O
	
rM   )
trio_tokenc                G   s   |rt |tstd|s@z
tj}W n ty>   tdY n0 ztj  W n ty`   Y n
0 tdt	
 }||j| ||| |  S )zHelper function for from_thread.run and from_thread.run_sync.

    Since this internally uses TrioToken.run_sync_soon, all warnings about
    raised exceptions canceling all tasks should be noted.
    z0Passed kwarg trio_token is not of type TrioTokenz=this thread wasn't created by Trio, pass kwarg trio_token=...z2this is a blocking function; call it from a thread)
isinstancer	   RuntimeErrorr0   r1   AttributeErrorr*   r+   rD   stdlib_queueSimpleQueuer>   rK   r   r#   )cbfnrL   rN   r:   qr   r   r   _run_fn_as_system_task   s"    

rW   c                G   s8   dd }t  }|tjd t|| g|R ||dS )a  Run the given async function in the parent Trio thread, blocking until it
    is complete.

    Returns:
      Whatever ``afn(*args)`` returns.

    Returns or raises whatever the given function returns or raises. It
    can also raise exceptions of its own:

    Raises:
        RunFinishedError: if the corresponding call to :func:`trio.run` has
            already completed, or if the run has started its final cleanup phase
            and can no longer spawn new system tasks.
        Cancelled: if the corresponding call to :func:`trio.run` completes
            while ``afn(*args)`` is running, then ``afn`` is likely to raise
            :exc:`trio.Cancelled`, and this will propagate out into
        RuntimeError: if you try calling this from inside the Trio thread,
            which would otherwise cause a deadlock.
        AttributeError: if no ``trio_token`` was provided, and we can't infer
            one from context.
        TypeError: if ``afn`` is not an asynchronous function.

    **Locating a Trio Token**: There are two ways to specify which
    `trio.run` loop to reenter:

        - Spawn this thread from `trio.to_thread.run_sync`. Trio will
          automatically capture the relevant Trio token and use it when you
          want to re-enter Trio.
        - Pass a keyword argument, ``trio_token`` specifying a specific
          `trio.run` loop to re-enter. This is useful in case you have a
          "foreign" thread, spawned using some other framework, and still want
          to enter Trio.
    c              
      sl   t  fddfdd}t }ztjj| |d W n( tyf   t	t
d Y n0 d S )Nc                     s   t  gR  } | I d H S r"   r   )coro)afnr:   r   r   unprotected_afn  s    z:from_thread_run.<locals>.callback.<locals>.unprotected_afnc                      s     tI d H  d S r"   )
put_nowaitr(   Zacapturer   )rV   rZ   r   r   await_in_trio_thread_task"  s    zDfrom_thread_run.<locals>.callback.<locals>.await_in_trio_thread_task)r    rL   zsystem nursery is closed)r   rG   rH   r*   r+   Zspawn_system_taskrP   r[   r(   Errorr?   )rV   rY   r:   r\   rL   r   )rY   r:   rV   rZ   r   callback  s    
z!from_thread_run.<locals>.callbackr*   rL   rN   )rG   rH   rK   r   r   rW   )rY   rN   r:   r^   rL   r   r   r   from_thread_run   s    #r`   c                G   s*   dd }t  }t|| g|R ||dS )a  Run the given sync function in the parent Trio thread, blocking until it
    is complete.

    Returns:
      Whatever ``fn(*args)`` returns.

    Returns or raises whatever the given function returns or raises. It
    can also raise exceptions of its own:

    Raises:
        RunFinishedError: if the corresponding call to `trio.run` has
            already completed.
        RuntimeError: if you try calling this from inside the Trio thread,
            which would otherwise cause a deadlock.
        AttributeError: if no ``trio_token`` was provided, and we can't infer
            one from context.
        TypeError: if ``fn`` is an async function.

    **Locating a Trio Token**: There are two ways to specify which
    `trio.run` loop to reenter:

        - Spawn this thread from `trio.to_thread.run_sync`. Trio will
          automatically capture the relevant Trio token and use it when you
          want to re-enter Trio.
        - Pass a keyword argument, ``trio_token`` specifying a specific
          `trio.run` loop to re-enter. This is useful in case you have a
          "foreign" thread, spawned using some other framework, and still want
          to enter Trio.
    c                    s4   t d t fdd}t|}| | d S )Nr*   c                     s4     } t | r0|   tdtd| S r/   )r2   r3   r4   r5   r6   r7   r8   r:   rU   r   r   unprotected_fn\  s    

z>from_thread_run_sync.<locals>.callback.<locals>.unprotected_fn)r   r   r   r(   r)   r[   )rV   rU   r:   rb   resr   ra   r   r^   Y  s
    

z&from_thread_run_sync.<locals>.callbackr_   )rG   rH   rW   )rU   rN   r:   r^   rL   r   r   r   from_thread_run_sync:  s    rd   )#rG   	threadingqueuerR   rI   	itertoolsr   r   r2   r(   Zsniffior   r*   Z_syncr   Z_corer   r   r   r	   r
   Z_utilr   localr0   r   r   rF   r   sr   rM   rW   r`   rd   r   r   r   r   <module>   s2    A