zmc
2023-08-08 e792e9a60d958b93aef96050644f369feb25d61b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
U
Z±dÑ6ã@sddlZddlZddlZddlZddlmZddlZddlZddl    Z    ddl
m Z ddl Z ddl mZddlmZmZmZmZmZddlmZe ¡ZedƒZd    ZeƒZd
d „Zejd d d dGdd„dƒƒZed ddœdd„ƒZddœdd„Z ddœdd„Z!ddœdd„Z"dS)éN)Úcount)Úcurrent_async_library_cvaré)ÚCapacityLimiter)Úenable_ki_protectionÚdisable_ki_protectionÚRunVarÚ    TrioTokenÚstart_thread_soon©Úcoroutine_or_errorÚlimiteré(cCs8z t ¡}Wn&tk
r2ttƒ}t |¡YnX|S)zÚGet 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úDd:\z\workplace\vscode\pyvenv\venv\Lib\site-packages\trio/_threads.pyÚcurrent_default_thread_limiter$s  rTF)ÚfrozenÚeqÚhashc@seZdZe ¡ZdS)ÚThreadPlaceholderN)Ú__name__Ú
__module__Ú __qualname__ÚattrÚibÚnamerrrrr8sr)Ú cancellabler c
‡sîtj ¡IdHtˆƒ‰ˆdkr&tƒ‰tj ¡g‰dttƒ›}t|ƒ‰‡‡‡fdd„‰tj     ¡‰‡‡‡fdd„}t
  ¡}t   |j|¡}‡‡fdd„}ˆ ˆ¡IdHzt||ƒWnˆ ˆ¡‚YnX‡‡fd    d
„}    tj |    ¡IdHS) uConvert 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.
 
    Nztrio.to_thread.run_sync-cs<‡‡‡fdd„}t |¡‰ˆddk    r8tj ˆdˆ¡dS)Nc    sz ˆ ¡W¢Sˆ ˆ¡XdS©N)Úrelease_on_behalf_ofÚunwrapr)r Ú placeholderÚresultrrÚ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_fncsTt d¡ˆt_z8ˆˆŽ}t |¡rB| ¡td t    ˆdˆƒ¡ƒ‚|W¢St`XdS©NzBTrio expected a sync function, but {!r} appears to be asynchronousr)
rrÚ TOKEN_LOCALÚtokenÚinspectÚ iscoroutineÚcloseÚ    TypeErrorÚformatÚgetattr©Úret)ÚargsÚcurrent_trio_tokenÚsync_fnrrÚ    worker_fn«s
 
 
ÿÿz%to_thread_run_sync.<locals>.worker_fncs,zˆ ˆ|¡Wntjk
r&YnXdSr")Ú run_sync_soonr*ÚRunFinishedErrorr-)r;r.rrÚdeliver_worker_fn_resultÀsz4to_thread_run_sync.<locals>.deliver_worker_fn_resultcs$ˆrdˆd<tjjjStjjjSdS)Nr)r*r+ZAbortZ    SUCCEEDEDZFAILED)Ú_)r!r,rrÚabortÐs
z!to_thread_run_sync.<locals>.abort)r*r+Zcheckpoint_if_cancelledÚboolrÚ current_taskÚnextÚ_thread_counterrr;Ú contextvarsÚ copy_contextÚ    functoolsÚpartialÚrunZacquire_on_behalf_ofr
r#Zwait_task_rescheduled)
r<r!r r:r r=ÚcontextZcontextvars_aware_worker_fnr@rBr)r:r!r;r r%r.r<r,rÚto_thread_run_sync=s*O 
    
rM)Ú
trio_tokencGs–|rt|tƒstdƒ‚|sBz
tj}Wntk
r@tdƒ‚YnXztj ¡Wntk
rdYn
Xtdƒ‚t     
¡}|  |j ||||¡|  ¡ ¡S)zÉHelper 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    Ú RuntimeErrorr0r1ÚAttributeErrorr*r+rDÚ stdlib_queueÚ SimpleQueuer>rKrr$)ÚcbÚfnrLrNr:ÚqrrrÚ_run_fn_as_system_taskÚs"
ÿ
rWcGs6dd„}t ¡}| tjd¡t||f|ž||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
snt‡‡fdd„ƒ‰‡‡fdd„}t ¡}ztjj|ˆ|dWn*tk
rhˆ t     t 
d¡¡¡YnXdS)Nc“stˆfˆžŽ}|IdHSr"r )Úcoro)Úafnr:rrÚunprotected_afnsz:from_thread_run.<locals>.callback.<locals>.unprotected_afnc“sˆ t ˆ¡IdH¡dSr")Ú
put_nowaitr(Zacapturer)rVrZrrÚawait_in_trio_thread_task"szDfrom_thread_run.<locals>.callback.<locals>.await_in_trio_thread_task)r rLzsystem nursery is closed) rrGrHr*r+Zspawn_system_taskrPr[r(ÚErrorr?)rVrYr:r\rLr)rYr:rVrZrÚcallbacksÿ
ÿz!from_thread_run.<locals>.callbackr*©rLrN)rGrHrKrrrW)rYrNr:r^rLrrrÚfrom_thread_runùs#þýûr`cGs(dd„}t ¡}t||f|ž||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.
    cs4t d¡t‡‡fdd„ƒ}t |¡}| |¡dS)Nr*cs4ˆˆŽ}t |¡r0| ¡td tˆdˆƒ¡ƒ‚|Sr/)r2r3r4r5r6r7r8©r:rUrrÚunprotected_fn\s
 
ÿÿz>from_thread_run_sync.<locals>.callback.<locals>.unprotected_fn)rrrr(r)r[)rVrUr:rbÚresrrarr^Ys
 
 
z&from_thread_run_sync.<locals>.callbackr_)rGrHrW)rUrNr:r^rLrrrÚfrom_thread_run_sync:sþýûrd)#rGÚ    threadingÚqueuerRrIÚ    itertoolsrrr2r(Zsniffiorr*Z_syncrZ_corerrrr    r
Z_utilr Úlocalr0rrrFrÚsrrMrWr`rdrrrrÚ<module>s2    A