ez-a-sync 0.32.24__cp312-cp312-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of ez-a-sync might be problematic. Click here for more details.

Files changed (177) hide show
  1. a_sync/ENVIRONMENT_VARIABLES.py +42 -0
  2. a_sync/__init__.pxd +2 -0
  3. a_sync/__init__.py +145 -0
  4. a_sync/_smart.c +22686 -0
  5. a_sync/_smart.cpython-312-i386-linux-gnu.so +0 -0
  6. a_sync/_smart.pxd +2 -0
  7. a_sync/_smart.pyi +202 -0
  8. a_sync/_smart.pyx +674 -0
  9. a_sync/_typing.py +258 -0
  10. a_sync/a_sync/__init__.py +60 -0
  11. a_sync/a_sync/_descriptor.c +19749 -0
  12. a_sync/a_sync/_descriptor.cpython-312-i386-linux-gnu.so +0 -0
  13. a_sync/a_sync/_descriptor.pyi +34 -0
  14. a_sync/a_sync/_descriptor.pyx +422 -0
  15. a_sync/a_sync/_flags.c +5687 -0
  16. a_sync/a_sync/_flags.cpython-312-i386-linux-gnu.so +0 -0
  17. a_sync/a_sync/_flags.pxd +3 -0
  18. a_sync/a_sync/_flags.pyx +92 -0
  19. a_sync/a_sync/_helpers.c +13722 -0
  20. a_sync/a_sync/_helpers.cpython-312-i386-linux-gnu.so +0 -0
  21. a_sync/a_sync/_helpers.pxd +3 -0
  22. a_sync/a_sync/_helpers.pyi +10 -0
  23. a_sync/a_sync/_helpers.pyx +167 -0
  24. a_sync/a_sync/_kwargs.c +10672 -0
  25. a_sync/a_sync/_kwargs.cpython-312-i386-linux-gnu.so +0 -0
  26. a_sync/a_sync/_kwargs.pxd +2 -0
  27. a_sync/a_sync/_kwargs.pyx +64 -0
  28. a_sync/a_sync/_meta.py +210 -0
  29. a_sync/a_sync/abstract.c +11350 -0
  30. a_sync/a_sync/abstract.cpython-312-i386-linux-gnu.so +0 -0
  31. a_sync/a_sync/abstract.pyi +141 -0
  32. a_sync/a_sync/abstract.pyx +221 -0
  33. a_sync/a_sync/base.c +14066 -0
  34. a_sync/a_sync/base.cpython-312-i386-linux-gnu.so +0 -0
  35. a_sync/a_sync/base.pyi +60 -0
  36. a_sync/a_sync/base.pyx +271 -0
  37. a_sync/a_sync/config.py +168 -0
  38. a_sync/a_sync/decorator.py +651 -0
  39. a_sync/a_sync/flags.c +4471 -0
  40. a_sync/a_sync/flags.cpython-312-i386-linux-gnu.so +0 -0
  41. a_sync/a_sync/flags.pxd +72 -0
  42. a_sync/a_sync/flags.pyi +74 -0
  43. a_sync/a_sync/flags.pyx +72 -0
  44. a_sync/a_sync/function.c +38189 -0
  45. a_sync/a_sync/function.cpython-312-i386-linux-gnu.so +0 -0
  46. a_sync/a_sync/function.pxd +28 -0
  47. a_sync/a_sync/function.pyi +571 -0
  48. a_sync/a_sync/function.pyx +1381 -0
  49. a_sync/a_sync/method.c +30587 -0
  50. a_sync/a_sync/method.cpython-312-i386-linux-gnu.so +0 -0
  51. a_sync/a_sync/method.pxd +9 -0
  52. a_sync/a_sync/method.pyi +524 -0
  53. a_sync/a_sync/method.pyx +1023 -0
  54. a_sync/a_sync/modifiers/__init__.pxd +1 -0
  55. a_sync/a_sync/modifiers/__init__.py +101 -0
  56. a_sync/a_sync/modifiers/cache/__init__.py +160 -0
  57. a_sync/a_sync/modifiers/cache/memory.py +165 -0
  58. a_sync/a_sync/modifiers/limiter.py +132 -0
  59. a_sync/a_sync/modifiers/manager.c +14939 -0
  60. a_sync/a_sync/modifiers/manager.cpython-312-i386-linux-gnu.so +0 -0
  61. a_sync/a_sync/modifiers/manager.pxd +5 -0
  62. a_sync/a_sync/modifiers/manager.pyi +219 -0
  63. a_sync/a_sync/modifiers/manager.pyx +299 -0
  64. a_sync/a_sync/modifiers/semaphores.py +173 -0
  65. a_sync/a_sync/property.c +28130 -0
  66. a_sync/a_sync/property.cpython-312-i386-linux-gnu.so +0 -0
  67. a_sync/a_sync/property.pyi +376 -0
  68. a_sync/a_sync/property.pyx +820 -0
  69. a_sync/a_sync/singleton.py +63 -0
  70. a_sync/aliases.py +3 -0
  71. a_sync/async_property/__init__.pxd +1 -0
  72. a_sync/async_property/__init__.py +1 -0
  73. a_sync/async_property/cached.c +20542 -0
  74. a_sync/async_property/cached.cpython-312-i386-linux-gnu.so +0 -0
  75. a_sync/async_property/cached.pxd +10 -0
  76. a_sync/async_property/cached.pyi +45 -0
  77. a_sync/async_property/cached.pyx +178 -0
  78. a_sync/async_property/proxy.c +36410 -0
  79. a_sync/async_property/proxy.cpython-312-i386-linux-gnu.so +0 -0
  80. a_sync/async_property/proxy.pxd +2 -0
  81. a_sync/async_property/proxy.pyi +124 -0
  82. a_sync/async_property/proxy.pyx +474 -0
  83. a_sync/asyncio/__init__.pxd +6 -0
  84. a_sync/asyncio/__init__.py +164 -0
  85. a_sync/asyncio/as_completed.c +18198 -0
  86. a_sync/asyncio/as_completed.cpython-312-i386-linux-gnu.so +0 -0
  87. a_sync/asyncio/as_completed.pxd +8 -0
  88. a_sync/asyncio/as_completed.pyi +109 -0
  89. a_sync/asyncio/as_completed.pyx +269 -0
  90. a_sync/asyncio/create_task.c +15109 -0
  91. a_sync/asyncio/create_task.cpython-312-i386-linux-gnu.so +0 -0
  92. a_sync/asyncio/create_task.pxd +2 -0
  93. a_sync/asyncio/create_task.pyi +51 -0
  94. a_sync/asyncio/create_task.pyx +276 -0
  95. a_sync/asyncio/gather.c +15735 -0
  96. a_sync/asyncio/gather.cpython-312-i386-linux-gnu.so +0 -0
  97. a_sync/asyncio/gather.pyi +107 -0
  98. a_sync/asyncio/gather.pyx +218 -0
  99. a_sync/asyncio/igather.c +11984 -0
  100. a_sync/asyncio/igather.cpython-312-i386-linux-gnu.so +0 -0
  101. a_sync/asyncio/igather.pxd +1 -0
  102. a_sync/asyncio/igather.pyi +7 -0
  103. a_sync/asyncio/igather.pyx +182 -0
  104. a_sync/asyncio/sleep.c +8916 -0
  105. a_sync/asyncio/sleep.cpython-312-i386-linux-gnu.so +0 -0
  106. a_sync/asyncio/sleep.pyi +14 -0
  107. a_sync/asyncio/sleep.pyx +49 -0
  108. a_sync/debugging.c +15157 -0
  109. a_sync/debugging.cpython-312-i386-linux-gnu.so +0 -0
  110. a_sync/debugging.pyi +76 -0
  111. a_sync/debugging.pyx +107 -0
  112. a_sync/exceptions.c +13169 -0
  113. a_sync/exceptions.cpython-312-i386-linux-gnu.so +0 -0
  114. a_sync/exceptions.pyi +376 -0
  115. a_sync/exceptions.pyx +446 -0
  116. a_sync/executor.py +575 -0
  117. a_sync/functools.c +11489 -0
  118. a_sync/functools.cpython-312-i386-linux-gnu.so +0 -0
  119. a_sync/functools.pxd +7 -0
  120. a_sync/functools.pyi +33 -0
  121. a_sync/functools.pyx +139 -0
  122. a_sync/future.py +1497 -0
  123. a_sync/iter.c +37702 -0
  124. a_sync/iter.cpython-312-i386-linux-gnu.so +0 -0
  125. a_sync/iter.pxd +11 -0
  126. a_sync/iter.pyi +366 -0
  127. a_sync/iter.pyx +981 -0
  128. a_sync/primitives/__init__.pxd +1 -0
  129. a_sync/primitives/__init__.py +53 -0
  130. a_sync/primitives/_debug.c +14737 -0
  131. a_sync/primitives/_debug.cpython-312-i386-linux-gnu.so +0 -0
  132. a_sync/primitives/_debug.pxd +12 -0
  133. a_sync/primitives/_debug.pyi +52 -0
  134. a_sync/primitives/_debug.pyx +223 -0
  135. a_sync/primitives/_loggable.c +10569 -0
  136. a_sync/primitives/_loggable.cpython-312-i386-linux-gnu.so +0 -0
  137. a_sync/primitives/_loggable.pxd +4 -0
  138. a_sync/primitives/_loggable.pyi +66 -0
  139. a_sync/primitives/_loggable.pyx +102 -0
  140. a_sync/primitives/locks/__init__.pxd +8 -0
  141. a_sync/primitives/locks/__init__.py +17 -0
  142. a_sync/primitives/locks/counter.c +16972 -0
  143. a_sync/primitives/locks/counter.cpython-312-i386-linux-gnu.so +0 -0
  144. a_sync/primitives/locks/counter.pxd +12 -0
  145. a_sync/primitives/locks/counter.pyi +151 -0
  146. a_sync/primitives/locks/counter.pyx +260 -0
  147. a_sync/primitives/locks/event.c +16125 -0
  148. a_sync/primitives/locks/event.cpython-312-i386-linux-gnu.so +0 -0
  149. a_sync/primitives/locks/event.pxd +22 -0
  150. a_sync/primitives/locks/event.pyi +43 -0
  151. a_sync/primitives/locks/event.pyx +185 -0
  152. a_sync/primitives/locks/prio_semaphore.c +25204 -0
  153. a_sync/primitives/locks/prio_semaphore.cpython-312-i386-linux-gnu.so +0 -0
  154. a_sync/primitives/locks/prio_semaphore.pxd +25 -0
  155. a_sync/primitives/locks/prio_semaphore.pyi +217 -0
  156. a_sync/primitives/locks/prio_semaphore.pyx +597 -0
  157. a_sync/primitives/locks/semaphore.c +25813 -0
  158. a_sync/primitives/locks/semaphore.cpython-312-i386-linux-gnu.so +0 -0
  159. a_sync/primitives/locks/semaphore.pxd +21 -0
  160. a_sync/primitives/locks/semaphore.pyi +196 -0
  161. a_sync/primitives/locks/semaphore.pyx +454 -0
  162. a_sync/primitives/queue.py +1018 -0
  163. a_sync/py.typed +0 -0
  164. a_sync/sphinx/__init__.py +3 -0
  165. a_sync/sphinx/ext.py +289 -0
  166. a_sync/task.py +932 -0
  167. a_sync/utils/__init__.py +105 -0
  168. a_sync/utils/iterators.py +297 -0
  169. a_sync/utils/repr.c +14354 -0
  170. a_sync/utils/repr.cpython-312-i386-linux-gnu.so +0 -0
  171. a_sync/utils/repr.pyi +2 -0
  172. a_sync/utils/repr.pyx +73 -0
  173. ez_a_sync-0.32.24.dist-info/METADATA +367 -0
  174. ez_a_sync-0.32.24.dist-info/RECORD +177 -0
  175. ez_a_sync-0.32.24.dist-info/WHEEL +7 -0
  176. ez_a_sync-0.32.24.dist-info/licenses/LICENSE.txt +17 -0
  177. ez_a_sync-0.32.24.dist-info/top_level.txt +1 -0
a_sync/executor.py ADDED
@@ -0,0 +1,575 @@
1
+ """
2
+ This module provides several executor classes that facilitate running synchronous functions asynchronously using `asyncio`.
3
+
4
+ With these executors, you can run sync functions in your executor with `await executor.run(fn, *args, **kwargs)`.
5
+ The `executor.submit(fn, *args, **kwargs)` method works similarly to the `concurrent.futures` implementation but
6
+ returns an `asyncio.Future` instead of a `concurrent.futures.Future`.
7
+
8
+ Executor Classes:
9
+ - :class:`AsyncProcessPoolExecutor`: A process pool executor providing asynchronous run and submit methods, with support for synchronous mode
10
+ - :class:`AsyncThreadPoolExecutor`: A thread pool executor providing asynchronous run and submit methods, with support for synchronous mode
11
+ - :class:`PruningThreadPoolExecutor`: An :class:`AsyncThreadPoolExecutor` that prunes inactive threads after a timeout, ensuring at least one thread remains active to prevent locks.
12
+
13
+ See Also:
14
+ - :mod:`concurrent.futures` for the original synchronous executor implementations.
15
+ """
16
+
17
+ import asyncio
18
+ import concurrent.futures
19
+ import multiprocessing.context
20
+ import queue
21
+ import threading
22
+ import weakref
23
+ from asyncio import sleep
24
+ from asyncio.futures import _convert_future_exc
25
+ from concurrent.futures import _base, thread
26
+
27
+ from a_sync._typing import *
28
+ from a_sync.primitives._debug import _DebugDaemonMixin
29
+
30
+
31
+ TEN_MINUTES = 60 * 10
32
+
33
+ Initializer = Callable[..., object]
34
+
35
+
36
+ class _AsyncExecutorMixin(concurrent.futures.Executor, _DebugDaemonMixin):
37
+ """
38
+ A mixin for Executors to provide asynchronous run and submit methods.
39
+
40
+ This mixin allows executors to operate in both asynchronous (normal) mode and synchronous mode.
41
+ In asynchronous (normal) mode, functions are submitted to the executor and awaited.
42
+ In synchronous mode, functions are executed directly in the current thread.
43
+
44
+ Examples:
45
+ >>> async def example():
46
+ >>> result = await executor.run(some_function, arg1, arg2, kwarg1=value1)
47
+ >>> print(result)
48
+
49
+ See Also:
50
+ - :meth:`submit` for submitting functions to the executor.
51
+ """
52
+
53
+ sync_mode: bool
54
+ """
55
+ Indicates if the executor is in synchronous mode (max_workers == 0).
56
+
57
+ Examples:
58
+ >>> if executor.sync_mode:
59
+ >>> print("Executor is in synchronous mode.")
60
+ """
61
+
62
+ _max_workers: int
63
+
64
+ _workers: str
65
+ """The type of workers used."""
66
+
67
+ __slots__ = "_max_workers", "_initializer", "_initargs", "_broken", "_shutdown_lock"
68
+
69
+ async def run(self, fn: Callable[P, T], *args: P.args, **kwargs: P.kwargs):
70
+ """
71
+ A shorthand way to call `await asyncio.get_event_loop().run_in_executor(this_executor, fn, *args)`.
72
+ Doesn't `await this_executor.run(fn, *args)` look so much better?
73
+
74
+ In synchronous mode, the function is executed directly in the current thread.
75
+ In asynchronous mode, the function is submitted to the executor and awaited.
76
+
77
+ Args:
78
+ fn: The function to run.
79
+ *args: Positional arguments for the function.
80
+ **kwargs: Keyword arguments for the function.
81
+
82
+ Examples:
83
+ >>> async def example():
84
+ >>> result = await executor.run(some_function, arg1, arg2, kwarg1=value1)
85
+ >>> print(result)
86
+
87
+ See Also:
88
+ - :meth:`submit` for submitting functions to the executor.
89
+ """
90
+ return fn(*args, **kwargs) if self.sync_mode else await self.submit(fn, *args, **kwargs)
91
+
92
+ @overload
93
+ def submit(self, fn: Callable[P, T], *args: P.args, fire_and_forget: Literal[True], **kwargs: P.kwargs) -> None: # type: ignore [override]
94
+ """
95
+ Submits a job to the executor without expecting a result back. The executor will execute the task silently.
96
+
97
+ Args:
98
+ fn: The function to submit.
99
+ *args: Positional arguments for the function.
100
+ fire_and_forget: True
101
+ **kwargs: Keyword arguments for the function.
102
+
103
+ Examples:
104
+ >>> executor.submit(some_function, arg1, arg2, fire_and_forget=True, kwarg1=value1)
105
+
106
+ See Also:
107
+ - :meth:`run` for running functions with the executor.
108
+ """
109
+
110
+ @overload
111
+ def submit(self, fn: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> "asyncio.Future[T]": # type: ignore [override]
112
+ """
113
+ Submits a job to the executor and returns an :class:`asyncio.Future` that can be awaited for the result without blocking.
114
+
115
+ Args:
116
+ fn: The function to submit.
117
+ *args: Positional arguments for the function.
118
+ **kwargs: Keyword arguments for the function.
119
+
120
+ Examples:
121
+ >>> future = executor.submit(some_function, arg1, arg2, kwarg1=value1)
122
+ >>> result = await future
123
+ >>> print(result)
124
+
125
+ See Also:
126
+ - :meth:`run` for running functions with the executor.
127
+ """
128
+
129
+ def submit(self, fn: Callable[P, T], *args: P.args, fire_and_forget: bool = False, **kwargs: P.kwargs) -> Optional["asyncio.Future[T]"]: # type: ignore [override]
130
+ # sourcery skip: simplify-boolean-comparison
131
+ """
132
+ Submits a job to the executor and returns an :class:`asyncio.Future` that can be awaited for the result without blocking.
133
+
134
+ If `fire_and_forget` is True, the executor will not return any data and intead of a :class:`~Future` this function will return `None`.
135
+
136
+ Args:
137
+ fn: The function to submit.
138
+ *args: Positional arguments for the function.
139
+ fire_and_forget (optional): Set True to send the job to the executor without expecting a result. If `fire_and_forget` is True, this function will return None instead of a Future. Default False.
140
+ **kwargs: Keyword arguments for the function.
141
+
142
+ Examples:
143
+ >>> future = executor.submit(some_function, arg1, arg2, kwarg1=value1)
144
+ >>> result = await future
145
+ >>> print(result)
146
+
147
+ See Also:
148
+ - :meth:`run` for running functions with the executor.
149
+ """
150
+ if fire_and_forget is True:
151
+ # Send the job to the executor and return without creating a future or setting up callbacks
152
+ if self.sync_mode:
153
+ fn(*args, **kwargs)
154
+ else:
155
+ self.__super_submit(fn, *args, **kwargs)
156
+ return None
157
+
158
+ loop = self._get_loop()
159
+ fut = loop.create_future()
160
+ if self.sync_mode:
161
+ try:
162
+ _set_fut_result(fut, fn(*args, **kwargs))
163
+ except Exception as e:
164
+ _set_fut_exception(fut, e)
165
+ else:
166
+ self._ensure_debug_daemon(fut, fn, *args, **kwargs)
167
+
168
+ cf_fut = self.__super_submit(fn, *args, **kwargs)
169
+
170
+ # TODO: implement logic to actually cancel the job, not just the future which is useless for our use case
171
+ # def _call_check_cancel(destination: asyncio.Future):
172
+ # if _fut_is_cancelled(destination):
173
+ # cf_fut.cancel()
174
+ #
175
+ # fut.add_done_callback(_call_check_cancel)
176
+
177
+ def _call_copy_future_state(cf_fut: "concurrent.futures.Future"):
178
+ if _fut_is_cancelled(fut):
179
+ return
180
+ loop.call_soon_threadsafe(
181
+ _copy_future_state,
182
+ cf_fut,
183
+ fut,
184
+ )
185
+
186
+ _add_done_callback(cf_fut, _call_copy_future_state)
187
+
188
+ return fut
189
+
190
+ def __repr__(self) -> str:
191
+ worker_info = f"[{self.worker_count_current}/{self._max_workers} {self._workers}]"
192
+ identifier = getattr(self, "_thread_name_prefix", None) or hex(id(self))
193
+ return f"<{self.__class__.__name__} {identifier} {worker_info}>"
194
+
195
+ def __len__(self) -> int:
196
+ # NOTE: should this be queue length instead? probably
197
+ return self.worker_count_current
198
+
199
+ @property
200
+ def worker_count_current(self) -> int:
201
+ """
202
+ Returns the current number of workers.
203
+
204
+ Examples:
205
+ >>> print(f"Current worker count: {executor.worker_count_current}")
206
+ """
207
+ return len(getattr(self, f"_{self._workers}"))
208
+
209
+ def __init_mixin__(self):
210
+ self.sync_mode = self._max_workers == 0
211
+ self.__super_submit = super().submit
212
+
213
+ async def _debug_daemon(self, fut: asyncio.Future, fn, *args, **kwargs) -> None:
214
+ """
215
+ Runs until manually cancelled by the finished work item.
216
+
217
+ This code will only run if `self.logger.isEnabledFor(logging.DEBUG)` is True. You do not need to include any level checks in your custom implementations.
218
+
219
+ Args:
220
+ fut: The future being debugged.
221
+ fn: The function being executed.
222
+ *args: Positional arguments for the function.
223
+ **kwargs: Keyword arguments for the function.
224
+
225
+ See Also:
226
+ - :meth:`_start_debug_daemon` to start the debug daemon.
227
+ """
228
+ # TODO: make prettier strings for other types
229
+ if type(fn).__name__ == "function":
230
+ fnid = getattr(fn, "__qualname__", fn.__name__)
231
+ if fn.__module__:
232
+ fnid = f"{fn.__module__}.{fnid}"
233
+ else:
234
+ fnid = fn
235
+
236
+ msg = f"%s processing %s{args}"
237
+ if kwargs:
238
+ msg = f"{msg[:-1]} {', '.join(f'{k}={v}' for k, v in kwargs.items())})"
239
+ else:
240
+ msg = f"{msg[:-2]})"
241
+
242
+ done = fut.done
243
+ log_debug = self.logger.debug
244
+
245
+ while not done():
246
+ await sleep(15)
247
+ if not done():
248
+ log_debug(msg, self, fnid)
249
+
250
+
251
+ # Process
252
+
253
+
254
+ class AsyncProcessPoolExecutor(_AsyncExecutorMixin, concurrent.futures.ProcessPoolExecutor):
255
+ """
256
+ A :class:`concurrent.futures.ProcessPoolExecutor' subclass providing asynchronous
257
+ run and submit methods that support kwargs, with support for synchronous mode
258
+
259
+ Examples:
260
+ >>> executor = AsyncProcessPoolExecutor(max_workers=4)
261
+ >>> future = executor.submit(some_function, arg1, arg2, kwarg1='kwarg1')
262
+ >>> result = await future
263
+ """
264
+
265
+ _workers = "processes"
266
+ """The type of workers used, set to "processes"."""
267
+
268
+ __slots__ = (
269
+ "_mp_context",
270
+ "_processes",
271
+ "_pending_work_items",
272
+ "_call_queue",
273
+ "_result_queue",
274
+ "_queue_management_thread",
275
+ "_queue_count",
276
+ "_shutdown_thread",
277
+ "_work_ids",
278
+ "_queue_management_thread_wakeup",
279
+ )
280
+
281
+ def __init__(
282
+ self,
283
+ max_workers: Optional[int] = None,
284
+ mp_context: Optional[multiprocessing.context.BaseContext] = None,
285
+ initializer: Optional[Initializer] = None,
286
+ initargs: Tuple[Any, ...] = (),
287
+ ) -> None:
288
+ """
289
+ Initializes the AsyncProcessPoolExecutor.
290
+
291
+ Args:
292
+ max_workers: The maximum number of workers. Defaults to None.
293
+ mp_context: The multiprocessing context. Defaults to None.
294
+ initializer: An initializer callable. Defaults to None.
295
+ initargs: Arguments for the initializer. Defaults to ().
296
+
297
+ Examples:
298
+ >>> executor = AsyncProcessPoolExecutor(max_workers=4)
299
+ >>> future = executor.submit(some_function, arg1, arg2)
300
+ >>> result = await future
301
+ """
302
+ if max_workers == 0:
303
+ concurrent.futures.ProcessPoolExecutor.__init__(
304
+ self, 1, mp_context, initializer, initargs
305
+ )
306
+ self._max_workers = 0
307
+ else:
308
+ concurrent.futures.ProcessPoolExecutor.__init__(
309
+ self, max_workers, mp_context, initializer, initargs
310
+ )
311
+ self.__init_mixin__()
312
+
313
+
314
+ # Thread
315
+
316
+
317
+ class AsyncThreadPoolExecutor(_AsyncExecutorMixin, concurrent.futures.ThreadPoolExecutor):
318
+ """
319
+ A :class:`concurrent.futures.ThreadPoolExecutor' subclass providing asynchronous
320
+ run and submit methods that support kwargs, with support for synchronous mode
321
+
322
+ Examples:
323
+ >>> executor = AsyncThreadPoolExecutor(max_workers=10, thread_name_prefix="MyThread")
324
+ >>> future = executor.submit(some_function, arg1, arg2, kwarg1='kwarg1')
325
+ >>> result = await future
326
+ """
327
+
328
+ _workers = "threads"
329
+ """The type of workers used, set to "threads"."""
330
+
331
+ __slots__ = (
332
+ "_work_queue",
333
+ "_idle_semaphore",
334
+ "_threads",
335
+ "_shutdown",
336
+ "_thread_name_prefix",
337
+ )
338
+
339
+ def __init__(
340
+ self,
341
+ max_workers: Optional[int] = None,
342
+ thread_name_prefix: str = "",
343
+ initializer: Optional[Initializer] = None,
344
+ initargs: Tuple[Any, ...] = (),
345
+ ) -> None:
346
+ """
347
+ Initializes the AsyncThreadPoolExecutor.
348
+
349
+ Args:
350
+ max_workers: The maximum number of workers. Defaults to None.
351
+ thread_name_prefix: Prefix for thread names. Defaults to ''.
352
+ initializer: An initializer callable. Defaults to None.
353
+ initargs: Arguments for the initializer. Defaults to ().
354
+
355
+ Examples:
356
+ >>> executor = AsyncThreadPoolExecutor(max_workers=10, thread_name_prefix="MyThread")
357
+ >>> future = executor.submit(some_function, arg1, arg2)
358
+ >>> result = await future
359
+ """
360
+ if max_workers == 0:
361
+ concurrent.futures.ThreadPoolExecutor.__init__(
362
+ self, 1, thread_name_prefix, initializer, initargs
363
+ )
364
+ self._max_workers = 0
365
+ else:
366
+ concurrent.futures.ThreadPoolExecutor.__init__(
367
+ self, max_workers, thread_name_prefix, initializer, initargs
368
+ )
369
+ self.__init_mixin__()
370
+
371
+
372
+ AsyncExecutor = Union[AsyncThreadPoolExecutor, AsyncProcessPoolExecutor]
373
+
374
+ # For backward-compatibility
375
+ ThreadPoolExecutor = AsyncThreadPoolExecutor
376
+ ProcessPoolExecutor = AsyncProcessPoolExecutor
377
+
378
+ # Pruning thread pool
379
+
380
+
381
+ def _worker(executor_reference, work_queue, initializer, initargs, timeout): # NOTE: NEW 'timeout'
382
+ """
383
+ Worker function for the PruningThreadPoolExecutor.
384
+
385
+ Args:
386
+ executor_reference: A weak reference to the executor.
387
+ work_queue: The work queue.
388
+ initializer: The initializer function.
389
+ initargs: Arguments for the initializer.
390
+ timeout: Timeout duration for pruning inactive threads.
391
+
392
+ See Also:
393
+ - :class:`PruningThreadPoolExecutor` for more details on thread pruning.
394
+ """
395
+ if initializer is not None:
396
+ try:
397
+ initializer(*initargs)
398
+ except BaseException:
399
+ _base.LOGGER.critical("Exception in initializer:", exc_info=True)
400
+ executor = executor_reference()
401
+ if executor is not None:
402
+ executor._initializer_failed()
403
+ return
404
+
405
+ try:
406
+ while True:
407
+ try: # NOTE: NEW
408
+ work_item = work_queue.get(block=True, timeout=timeout) # NOTE: NEW
409
+ except queue.Empty: # NOTE: NEW
410
+ # Its been 'timeout' seconds and there are no new work items. # NOTE: NEW
411
+ # Let's suicide the thread. # NOTE: NEW
412
+ executor = executor_reference() # NOTE: NEW
413
+
414
+ with executor._adjusting_lock: # NOTE: NEW
415
+ # NOTE: We keep a minimum of one thread active to prevent locks
416
+ if len(executor) > 1: # NOTE: NEW
417
+ t = threading.current_thread() # NOTE: NEW
418
+ executor._threads.remove(t) # NOTE: NEW
419
+ thread._threads_queues.pop(t) # NOTE: NEW
420
+ # Let the executor know we have one less idle thread available
421
+ executor._idle_semaphore.acquire(blocking=False) # NOTE: NEW
422
+ return # NOTE: NEW
423
+ continue
424
+
425
+ if work_item is not None:
426
+ work_item.run()
427
+ # Delete references to object. See issue16284
428
+ del work_item
429
+
430
+ # attempt to increment idle count
431
+ executor = executor_reference()
432
+ if executor is not None:
433
+ executor._idle_semaphore.release()
434
+ del executor
435
+ continue
436
+
437
+ executor = executor_reference()
438
+ # Exit if:
439
+ # - The interpreter is shutting down OR
440
+ # - The executor that owns the worker has been collected OR
441
+ # - The executor that owns the worker has been shutdown OR
442
+ if thread._shutdown or executor is None or executor._shutdown:
443
+ # Flag the executor as shutting down as early as possible if it is not gc-ed yet.
444
+ if executor is not None:
445
+ executor._shutdown = True
446
+ # Notice other workers
447
+ work_queue.put(None)
448
+ return
449
+ del executor
450
+ except BaseException:
451
+ _base.LOGGER.critical("Exception in worker", exc_info=True)
452
+
453
+
454
+ class PruningThreadPoolExecutor(AsyncThreadPoolExecutor):
455
+ """
456
+ This :class:`~AsyncThreadPoolExecutor` implementation prunes inactive threads after 'timeout' seconds without a work item.
457
+ Pruned threads will be automatically recreated as needed for future workloads. Up to 'max_threads' can be active at any one time.
458
+ The executor ensures that at least one active thread remains to prevent locks.
459
+
460
+ Note:
461
+ The `_worker` function includes a check (`len(executor) > 1`) to ensure that at least one thread remains active.
462
+ This prevents the executor from having zero active threads, which could lead to deadlocks.
463
+
464
+ Examples:
465
+ >>> executor = PruningThreadPoolExecutor(max_workers=5, timeout=300)
466
+ >>> future = executor.submit(some_function, arg1, arg2, kwarg1='kwarg1')
467
+ >>> result = await future
468
+ """
469
+
470
+ __slots__ = "_timeout", "_adjusting_lock"
471
+
472
+ def __init__(
473
+ self,
474
+ max_workers=None,
475
+ thread_name_prefix="",
476
+ initializer=None,
477
+ initargs=(),
478
+ timeout=TEN_MINUTES,
479
+ ):
480
+ """
481
+ Initializes the PruningThreadPoolExecutor.
482
+
483
+ Args:
484
+ max_workers: The maximum number of workers. Defaults to None.
485
+ thread_name_prefix: Prefix for thread names. Defaults to ''.
486
+ initializer: An initializer callable. Defaults to None.
487
+ initargs: Arguments for the initializer. Defaults to ().
488
+ timeout: Timeout duration for pruning inactive threads. Defaults to TEN_MINUTES.
489
+
490
+ Examples:
491
+ >>> executor = PruningThreadPoolExecutor(max_workers=5, timeout=300)
492
+ >>> future = executor.submit(some_function, arg1, arg2)
493
+ >>> result = await future
494
+ """
495
+
496
+ self._timeout = timeout
497
+ """Timeout duration for pruning inactive threads."""
498
+
499
+ self._adjusting_lock = threading.Lock()
500
+ """Lock used to adjust the number of threads."""
501
+
502
+ AsyncThreadPoolExecutor.__init__(
503
+ self, max_workers, thread_name_prefix, initializer, initargs
504
+ )
505
+
506
+ def __len__(self) -> int:
507
+ return len(self._threads)
508
+
509
+ def _adjust_thread_count(self):
510
+ """
511
+ Adjusts the number of threads based on workload and idle threads.
512
+
513
+ See Also:
514
+ - :func:`_worker` for the worker function that handles thread pruning.
515
+ """
516
+ with self._adjusting_lock:
517
+ # if idle threads are available, don't spin new threads
518
+ if self._idle_semaphore.acquire(timeout=0):
519
+ return
520
+
521
+ # When the executor gets lost, the weakref callback will wake up
522
+ # the worker threads.
523
+ def weakref_cb(_, q=self._work_queue):
524
+ q.put(None)
525
+
526
+ num_threads = len(self._threads)
527
+ if num_threads < self._max_workers:
528
+ thread_name = "%s_%d" % (self._thread_name_prefix or self, num_threads)
529
+ t = threading.Thread(
530
+ name=thread_name,
531
+ target=_worker,
532
+ args=(
533
+ weakref.ref(self, weakref_cb),
534
+ self._work_queue,
535
+ self._initializer,
536
+ self._initargs,
537
+ self._timeout,
538
+ ),
539
+ )
540
+ t.daemon = True
541
+ t.start()
542
+ self._threads.add(t)
543
+ thread._threads_queues[t] = self._work_queue
544
+
545
+
546
+ def _copy_future_state(cf_fut: concurrent.futures.Future, fut: asyncio.Future):
547
+ """Internal helper to copy state from another Future.
548
+
549
+ The other Future may be a concurrent.futures.Future.
550
+ """
551
+ # check this again in case it was cancelled since the last check
552
+ if _fut_is_cancelled(fut):
553
+ return
554
+ exception = _get_cf_fut_exception(cf_fut)
555
+ if exception is None:
556
+ _set_fut_result(fut, _get_cf_fut_result(cf_fut))
557
+ else:
558
+ _set_fut_exception(fut, _convert_future_exc(exception))
559
+
560
+
561
+ _fut_is_cancelled = asyncio.Future.cancelled
562
+ _get_cf_fut_result = concurrent.futures.Future.result
563
+ _get_cf_fut_exception = concurrent.futures.Future.exception
564
+ _set_fut_result = asyncio.Future.set_result
565
+ _set_fut_exception = asyncio.Future.set_exception
566
+ _add_done_callback = concurrent.futures.Future.add_done_callback
567
+
568
+
569
+ executor = PruningThreadPoolExecutor(128)
570
+
571
+ __all__ = [
572
+ "AsyncThreadPoolExecutor",
573
+ "AsyncProcessPoolExecutor",
574
+ "PruningThreadPoolExecutor",
575
+ ]