cs-threads 20250306__tar.gz

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.
@@ -0,0 +1,494 @@
1
+ Metadata-Version: 2.4
2
+ Name: cs-threads
3
+ Version: 20250306
4
+ Summary: threading and communication/synchronisation conveniences
5
+ Keywords: python2,python3
6
+ Author-email: Cameron Simpson <cs@cskk.id.au>
7
+ Description-Content-Type: text/markdown
8
+ Classifier: Programming Language :: Python
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
14
+ Classifier: License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)
15
+ Requires-Dist: cs.context>=20250306
16
+ Requires-Dist: cs.deco>=20250306
17
+ Requires-Dist: cs.excutils>=20250306
18
+ Requires-Dist: cs.gimmicks>=20240316
19
+ Requires-Dist: cs.pfx>=20241208
20
+ Requires-Dist: cs.py.func>=20240630
21
+ Requires-Dist: cs.py.stack>=20250306
22
+ Requires-Dist: cs.seq>=20250306
23
+ Project-URL: MonoRepo Commits, https://bitbucket.org/cameron_simpson/css/commits/branch/main
24
+ Project-URL: Monorepo Git Mirror, https://github.com/cameron-simpson/css
25
+ Project-URL: Monorepo Hg/Mercurial Mirror, https://hg.sr.ht/~cameron-simpson/css
26
+ Project-URL: Source, https://github.com/cameron-simpson/css/blob/main/lib/python/cs/threads.py
27
+
28
+ Thread related convenience classes and functions.
29
+
30
+ *Latest release 20250306*:
31
+ HasThreadState: various fixes.
32
+
33
+ ## <a name="AdjustableSemaphore"></a>Class `AdjustableSemaphore`
34
+
35
+ A semaphore whose value may be tuned after instantiation.
36
+
37
+ *`AdjustableSemaphore.acquire(self, blocking=True)`*:
38
+ The acquire() method calls the base acquire() method if not blocking.
39
+ If blocking is true, the base acquire() is called inside a lock to
40
+ avoid competing with a reducing adjust().
41
+
42
+ *`AdjustableSemaphore.adjust(self, newvalue)`*:
43
+ Set capacity to `newvalue`
44
+ by calling release() or acquire() an appropriate number of times.
45
+
46
+ If `newvalue` lowers the semaphore capacity then adjust()
47
+ may block until the overcapacity is released.
48
+
49
+ *`AdjustableSemaphore.adjust_delta(self, delta)`*:
50
+ Adjust capacity by `delta` by calling release() or acquire()
51
+ an appropriate number of times.
52
+
53
+ If `delta` lowers the semaphore capacity then adjust() may block
54
+ until the overcapacity is released.
55
+
56
+ *`AdjustableSemaphore.release(self)`*:
57
+ Release the semaphore.
58
+
59
+ ## <a name="bg"></a>`bg(func, *, daemon=None, name=None, no_start=False, no_logexc=False, args=None, kwargs=None, thread_factory=None, pre_enter_objects=None, **thread_factory_kw)`
60
+
61
+ Dispatch the callable `func` in its own `Thread`;
62
+ return the `Thread`.
63
+
64
+ Parameters:
65
+ * `func`: a callable for the `Thread` target.
66
+ * `args`, `kwargs`: passed to the `Thread` constructor
67
+ * `kwargs`, `kwargs`: passed to the `Thread` constructor
68
+ * `daemon`: optional argument specifying the `.daemon` attribute.
69
+ * `name`: optional argument specifying the `Thread` name,
70
+ default: the name of `func`.
71
+ * `no_logexc`: if false (default `False`), wrap `func` in `@logexc`.
72
+ * `no_start`: optional argument, default `False`.
73
+ If true, do not start the `Thread`.
74
+ * `pre_enter_objects`: an optional iterable of objects which
75
+ should be entered using `with`
76
+
77
+ If `pre_enter_objects` is supplied, these objects will be
78
+ entered before the `Thread` is started and exited when the
79
+ `Thread` target function ends.
80
+ If the `Thread` is _not_ started (`no_start=True`, very
81
+ unusual) then it will be the caller's responsibility to manage
82
+ to entered objects.
83
+
84
+ ## <a name="DeadlockError"></a>Class `DeadlockError(builtins.RuntimeError)`
85
+
86
+ Raised by `NRLock` when a lock is attempted from the `Thread` currently holding the lock.
87
+
88
+ ## <a name="HasThreadState"></a>Class `HasThreadState(cs.context.ContextManagerMixin)`
89
+
90
+ A mixin for classes with a `cs.threads.ThreadState` instance as `.state`
91
+ providing a context manager which pushes `current=self` onto that state
92
+ and a `default()` class method returning `cls.perthread_state.current`
93
+ as the default instance of that class.
94
+
95
+ *NOTE*: the documentation here refers to `cls.perthread_state`, but in
96
+ fact we honour the `cls.THREAD_STATE_ATTR` attribute to name
97
+ the state attribute which allows perclass state attributes,
98
+ and also use with classes which already use `.perthread_state` for
99
+ another purpose.
100
+
101
+ *NOTE*: `HasThreadState.Thread` is a _class_ method whose default
102
+ is to push state for all active `HasThreadState` subclasses.
103
+ Contrast with `HasThreadState.bg` which is an _instance_method
104
+ whose default is to push state for just that instance.
105
+ The top level `cs.threads.bg` function calls `HasThreadState.Thread`
106
+ to obtain its `Thread`.
107
+
108
+ *`HasThreadState.Thread(*, name=None, target, enter_objects=None, **Thread_kw)`*:
109
+ Factory for a `Thread` to push the `.current` state for the
110
+ currently active classes.
111
+
112
+ The optional parameter `enter_objects` may be used to pass
113
+ an iterable of objects whose contexts should be entered
114
+ using `with obj:`.
115
+ If this is set to `True` that indicates that every "current"
116
+ `HasThreadStates` instance should be entered.
117
+ The default does not enter any object contexts.
118
+ The `HasThreadStates.bg` method defaults to passing
119
+ `enter_objects=(self,)` to enter the context for `self`.
120
+
121
+ *`HasThreadState.__enter_exit__(self)`*:
122
+ Push `self.perthread_state.current=self` as the `Thread` local current instance.
123
+
124
+ Include `self.__class__` in the set of currently active classes for the duration.
125
+
126
+ *`HasThreadState.bg(self, func, *, enter_objects=None, **bg_kw)`*:
127
+ Get a `Thread` using `type(self).Thread` and start it.
128
+ Return the `Thread`.
129
+
130
+ The `HasThreadState.Thread` factory duplicates the current `Thread`'s
131
+ `HasThreadState` current objects as current in the new `Thread`.
132
+ Additionally it enters the contexts of various objects using
133
+ `with obj` according to the `enter_objects` parameter.
134
+
135
+ The value of the optional parameter `enter_objects` governs
136
+ which objects have their context entered using `with obj`
137
+ in the child `Thread` while running `func` as follows:
138
+ - `None`: the default, meaning `(self,)`
139
+ - `False`: no object contexts are entered
140
+ - `True`: all current `HasThreadState` object contexts will be entered
141
+ - an iterable of objects whose contexts will be entered;
142
+ pass `()` to enter no objects
143
+
144
+ *`HasThreadState.default(*, factory=None, raise_on_None=False)`*:
145
+ The default instance of this class from `cls.perthread_state.current`.
146
+
147
+ Parameters:
148
+ * `factory`: optional callable to create an instance of `cls`
149
+ if `cls.perthread_state.current` is `None` or missing;
150
+ if `factory` is `True` then `cls` is used as the factory
151
+ * `raise_on_None`: if `cls.perthread_state.current` is `None` or missing
152
+ and `factory` is false and `raise_on_None` is true,
153
+ raise a `RuntimeError`;
154
+ this is primarily a debugging aid
155
+
156
+ *`HasThreadState.get_thread_states(all_classes=None)`*:
157
+ Return a mapping of `class`->*current_instance*`
158
+ for use with `HasThreadState.with_thread_states`
159
+ or `HasThreadState.Thread` or `HasThreadState.bg`.
160
+
161
+ The default behaviour returns just a mapping for this class,
162
+ expecting the default instance to be responsible for what
163
+ other resources it holds.
164
+
165
+ There is also a legacy mode for `all_classes=True`
166
+ where the mapping is for all active classes,
167
+ probably best used for `Thread`s spawned outside
168
+ a `HasThreadState` context.
169
+
170
+ Parameters:
171
+ * `all_classes`: optional flag, default `False`;
172
+ if true, return a mapping of class to current instance
173
+ for all `HasThreadState` subclasses with an open instance,
174
+ otherwise just a mapping from this class to its current instance
175
+
176
+ ## <a name="joinif"></a>`joinif(T: threading.Thread)`
177
+
178
+ Call `T.join()` if `T` is not the current `Thread`.
179
+
180
+ Unlike `threading.Thread.join`, this function is a no-op if
181
+ `T` is the current `Thread.
182
+
183
+ The use case is situations such as the shutdown phase of the
184
+ `MultiOpenMixin.startup_shutdown` context manager. Because
185
+ the "initial open" startup phase is not necessarily run in
186
+ the same thread as the "final close" shutdown phase, it is
187
+ possible for example for a worker `Thread` to execute the
188
+ shutdown phase and try to join itself. Using this function
189
+ supports that scenario.
190
+
191
+ ## <a name="LockableMixin"></a>Class `LockableMixin`
192
+
193
+ Trite mixin to control access to an object via its `._lock` attribute.
194
+ Exposes the `._lock` as the property `.lock`.
195
+ Presents a context manager interface for obtaining an object's lock.
196
+
197
+ *`LockableMixin.__exit__(self, exc_type, exc_value, traceback)`*:
198
+ pylint: disable=unused-argument
199
+
200
+ *`LockableMixin.lock`*:
201
+ The internal lock object.
202
+
203
+ ## <a name="locked"></a>`locked(*da, **dkw)`
204
+
205
+ A decorator for instance methods that must run within a lock.
206
+
207
+ Decorator keyword arguments:
208
+ * `initial_timeout`:
209
+ the initial lock attempt timeout;
210
+ if this is `>0` and exceeded a warning is issued
211
+ and then an indefinite attempt is made.
212
+ Default: `2.0`s
213
+ * `lockattr`:
214
+ the name of the attribute of `self`
215
+ which references the lock object.
216
+ Default `'_lock'`
217
+
218
+ ## <a name="locked_property"></a>`locked_property(*da, **dkw)`
219
+
220
+ A thread safe property whose value is cached.
221
+ The lock is taken if the value needs to computed.
222
+
223
+ The default lock attribute is `._lock`.
224
+ The default attribute for the cached value is `._`*funcname*
225
+ where *funcname* is `func.__name__`.
226
+ The default "unset" value for the cache is `None`.
227
+
228
+ ## <a name="monitor"></a>`monitor(*da, **dkw)`
229
+
230
+ Turn a class into a monitor, all of whose public methods are `@locked`.
231
+
232
+ This is a simple approach which requires class instances to have a
233
+ `._lock` which is an `RLock` or compatible
234
+ because methods may naively call each other.
235
+
236
+ Parameters:
237
+ * `attrs`: optional iterable of attribute names to wrap in `@locked`.
238
+ If omitted, all names commencing with a letter are chosen.
239
+ * `initial_timeout`: optional initial lock timeout, default `10.0`s.
240
+ * `lockattr`: optional lock attribute name, default `'_lock'`.
241
+
242
+ Only attributes satifying `inspect.ismethod` are wrapped
243
+ because `@locked` requires access to the instance `._lock` attribute.
244
+
245
+ ## <a name="NRLock"></a>Class `NRLock`
246
+
247
+ A nonrecursive lock.
248
+ Attempting to take this lock when it is already held by the current `Thread`
249
+ will raise `DeadlockError`.
250
+ Otherwise this behaves like `threading.Lock`.
251
+
252
+ *`NRLock.acquire(self, *a, caller_frame=None, **kw)`*:
253
+ Acquire the lock as for `threading.Lock`.
254
+ Raises `DeadlockError` is the lock is already held by the current `Thread`.
255
+
256
+ *`NRLock.locked(self)`*:
257
+ Return the lock status.
258
+
259
+ *`NRLock.release(self)`*:
260
+ Release the lock as for `threading.Lock`.
261
+
262
+ ## <a name="PriorityLock"></a>Class `PriorityLock`
263
+
264
+ A priority based mutex which is acquired by and released to waiters
265
+ in priority order.
266
+
267
+ The initialiser sets a default priority, itself defaulting to `0`.
268
+
269
+ The `acquire()` method accepts an optional `priority` value
270
+ which specifies the priority of the acquire request;
271
+ lower values have higher priorities.
272
+ `acquire` returns a new `PriorityLockSubLock`.
273
+
274
+ Note that internally this allocates a `threading.Lock` per acquirer.
275
+
276
+ When `acquire` is called, if the `PriorityLock` is taken
277
+ then the acquirer blocks on their personal `Lock`.
278
+
279
+ When `release()` is called the highest priority `Lock` is released.
280
+
281
+ Within a priority level `acquire`s are served in FIFO order.
282
+
283
+ Used as a context manager, the mutex is obtained at the default priority.
284
+ The `priority()` method offers a context manager
285
+ with a specified priority.
286
+ Both context managers return the `PriorityLockSubLock`
287
+ allocated by the `acquire`.
288
+
289
+ *`PriorityLock.__init__(self, default_priority=0, name=None)`*:
290
+ Initialise the `PriorityLock`.
291
+
292
+ Parameters:
293
+ * `default_priority`: the default `acquire` priority,
294
+ default `0`.
295
+ * `name`: optional identifying name
296
+
297
+ *`PriorityLock.__enter__(self)`*:
298
+ Enter the mutex as a context manager at the default priority.
299
+ Returns the new `Lock`.
300
+
301
+ *`PriorityLock.__exit__(self, *_)`*:
302
+ Exit the context manager.
303
+
304
+ *`PriorityLock.acquire(self, priority=None)`*:
305
+ Acquire the mutex with `priority` (default from `default_priority`).
306
+ Return the new `PriorityLockSubLock`.
307
+
308
+ This blocks behind any higher priority `acquire`s
309
+ or any earlier `acquire`s of the same priority.
310
+
311
+ *`PriorityLock.priority(self, this_priority)`*:
312
+ A context manager with the specified `this_priority`.
313
+ Returns the new `Lock`.
314
+
315
+ *`PriorityLock.release(self)`*:
316
+ Release the mutex.
317
+
318
+ Internally, this releases the highest priority `Lock`,
319
+ allowing that `acquire`r to go forward.
320
+
321
+ ## <a name="PriorityLockSubLock"></a>Class `PriorityLockSubLock(PriorityLockSubLock)`
322
+
323
+ The record for the per-`acquire`r `Lock` held by `PriorityLock.acquire`.
324
+
325
+ ## <a name="State"></a>Class `State(_thread._local)`
326
+
327
+ A `Thread` local object with attributes
328
+ which can be used as a context manager to stack attribute values.
329
+
330
+ Example:
331
+
332
+ from cs.threads import ThreadState
333
+
334
+ S = ThreadState(verbose=False)
335
+
336
+ with S(verbose=True) as prev_attrs:
337
+ if S.verbose:
338
+ print("verbose! (formerly verbose=%s)" % prev_attrs['verbose'])
339
+
340
+ *`State.__init__(self, **kw)`*:
341
+ Initiate the `ThreadState`, providing the per-Thread initial values.
342
+
343
+ *`State.__call__(self, **kw)`*:
344
+ Calling a `ThreadState` returns a context manager which stacks some state.
345
+ The context manager yields the previous values
346
+ for the attributes which were stacked.
347
+
348
+ ## <a name="ThreadState"></a>Class `ThreadState(_thread._local)`
349
+
350
+ A `Thread` local object with attributes
351
+ which can be used as a context manager to stack attribute values.
352
+
353
+ Example:
354
+
355
+ from cs.threads import ThreadState
356
+
357
+ S = ThreadState(verbose=False)
358
+
359
+ with S(verbose=True) as prev_attrs:
360
+ if S.verbose:
361
+ print("verbose! (formerly verbose=%s)" % prev_attrs['verbose'])
362
+
363
+ *`ThreadState.__init__(self, **kw)`*:
364
+ Initiate the `ThreadState`, providing the per-Thread initial values.
365
+
366
+ *`ThreadState.__call__(self, **kw)`*:
367
+ Calling a `ThreadState` returns a context manager which stacks some state.
368
+ The context manager yields the previous values
369
+ for the attributes which were stacked.
370
+
371
+ ## <a name="via"></a>`via(cmanager, func, *a, **kw)`
372
+
373
+ Return a callable that calls the supplied `func` inside a
374
+ `with` statement using the context manager `cmanager`.
375
+ This intended use case is aimed at deferred function calls.
376
+
377
+ # Release Log
378
+
379
+
380
+
381
+ *Release 20250306*:
382
+ HasThreadState: various fixes.
383
+
384
+ *Release 20241005*:
385
+ Remove some debug noise.
386
+
387
+ *Release 20240630*:
388
+ * bg: use closeall instead of twostep/withall.
389
+ * HasThreadState.bg: drop pre_enter_objects (unused), gets plumbed by the **bg_kw.
390
+
391
+ *Release 20240422*:
392
+ HasThreadState.default: make factory and raise_on keyword only.
393
+
394
+ *Release 20240412*:
395
+ * New NRLock, an nonrecursive Lock and associated exception DeadlockError.
396
+ * bg: rename thread_class to thread_factory for clarity.
397
+ * HasThreadState: big refactor to separate the mapping of default instances from the previously automatic opening of a context for each.
398
+ * HasThreadState.bg: new optional pre_enter_objects to supply objects which should be opened before the Thread starts (before bg returns) and closed when the Thread exits.
399
+
400
+ *Release 20240316*:
401
+ Fixed release upload artifacts.
402
+
403
+ *Release 20240303*:
404
+ * HasThreadState: rename thread_states() to get_thread_states().
405
+ * HasThreadState.get_thread_states: some logic fixes.
406
+
407
+ *Release 20231129*:
408
+ * HasThreadState.thread_states: *policy change*: the default now makes a mapping only for this class, not for all HasThreadState subclasses, on the premise that this class can manage use of other classes if required.
409
+ * HasThreadState: new bg() class method like Thread() but also starting the Thread.
410
+
411
+ *Release 20230331*:
412
+ * HasThreadState: new thread_states() method to snapshot the current states.
413
+ * HasThreadState: new with_thread_states() context manager to apply a set of states.
414
+ * HasThreadState: rename the default state from .state to .perthread_state.
415
+ * HasThreadState.__enter_exit__: pass cls._HasThreadState_lock to stackset as the modification guard lock, prevents race in thread_states.
416
+ * Rename State to ThreadState, which how I always use it anyway, and leave a compatibility name behind.
417
+ * New joinif(Thread) method to join a Thread unless we are that Thread - this is because MultiOpenMixin.startup_shutdown stuff may run the shutdown in a differ Thread from that which ran the startup.
418
+ * @uses_runstate: use the prevailing RunState or create one.
419
+ * Drop Python 2 support.
420
+
421
+ *Release 20230212*:
422
+ * HasThreadState: maintain a set of the HasThreadState classes in use.
423
+ * New HasThreadState.Thread class factory method to create a new Thread with the current threads states at time of call instantiated in the new Thread.
424
+ * bg: new no_context=False parameter to suppress use of HasThreadState.Thread to create the new Thread.
425
+
426
+ *Release 20230125*:
427
+ New HasThreadState mixin for classes with a state=State() attribute to provide a cls.default() class method for the default instance and a context manager to push/pop self.state.current=self.
428
+
429
+ *Release 20221228*:
430
+ * Get error and warning from cs.gimmicks, breaks circular import with cs.logutils.
431
+ * Late import of cs.logutils.LogTime to avoid circular import.
432
+
433
+ *Release 20221207*:
434
+ Small bug fix.
435
+
436
+ *Release 20221118*:
437
+ REMOVE WorkerThreadPool, pulls in too many other things and was never used.
438
+
439
+ *Release 20211208*:
440
+ bg: do not pass the current Pfx prefix into the new Thread, seems to leak and grow.
441
+
442
+ *Release 20210306*:
443
+ bg: include the current Pfx prefix in the thread name and thread body Pfx, obsoletes cs.pfx.PfxThread.
444
+
445
+ *Release 20210123*:
446
+ New @monitor class decorator for simple RLock based reentrance protection.
447
+
448
+ *Release 20201025*:
449
+ * @locked: bump the default warning timeout to 10s, was firing too often.
450
+ * New State class for thread local state objects with default attribute values and a stacking __call__ context manager.
451
+
452
+ *Release 20200718*:
453
+ @locked: apply the interior __doc__ to the wrapper.
454
+
455
+ *Release 20200521*:
456
+ @locked_property: decorate with @cs.deco.decorator to support keyword arguments.
457
+
458
+ *Release 20191102*:
459
+ @locked: report slow-to-acquire locks, add initial_timeout and lockattr decorator keyword parameters.
460
+
461
+ *Release 20190923.2*:
462
+ Fix annoying docstring typo.
463
+
464
+ *Release 20190923.1*:
465
+ Docstring updates.
466
+
467
+ *Release 20190923*:
468
+ Remove dependence on cs.obj.
469
+
470
+ *Release 20190921*:
471
+ New PriorityLock class for a mutex which releases in (priority,fifo) order.
472
+
473
+ *Release 20190812*:
474
+ bg: compute default name before wrapping `func` in @logexc.
475
+
476
+ *Release 20190729*:
477
+ bg: provide default `name`, run callable inside Pfx, add optional no_logexc=False param preventing @logec wrapper if true.
478
+
479
+ *Release 20190422*:
480
+ bg(): new optional `no_start=False` keyword argument, preventing Thread.start if true
481
+
482
+ *Release 20190102*:
483
+ * Drop some unused classes.
484
+ * New LockableMixin, presenting a context manager and a .lock property.
485
+
486
+ *Release 20160828*:
487
+ Use "install_requires" instead of "requires" in DISTINFO.
488
+
489
+ *Release 20160827*:
490
+ * Replace bare "excepts" with "except BaseException".
491
+ * Doc updates. Other minor improvements.
492
+
493
+ *Release 20150115*:
494
+ First PyPI release.