@@ -227,6 +227,29 @@ def run(self):
227
227
self .running = False
228
228
229
229
230
+
231
+ if sys .version_info >= (3 , 7 ):
232
+ from contextlib import nullcontext
233
+ else :
234
+ class nullcontext (object ):
235
+ """Context manager that does no additional processing.
236
+ Used as a stand-in for a normal context manager, when a particular
237
+ block of code is only sometimes used with a normal context manager:
238
+ cm = optional_cm if condition else nullcontext()
239
+ with cm:
240
+ # Perform operation, using optional_cm if condition is True
241
+ """
242
+
243
+ def __init__ (self , enter_result = None ):
244
+ self .enter_result = enter_result
245
+
246
+ def __enter__ (self ):
247
+ return self .enter_result
248
+
249
+ def __exit__ (self , * excinfo ):
250
+ pass
251
+
252
+
230
253
class WorkerPool (object ):
231
254
""" A WorkerPool allows to spawn function executions
232
255
to threads, returning a reply object on which you
@@ -238,13 +261,14 @@ class WorkerPool(object):
238
261
when the pool received a trigger_shutdown().
239
262
"""
240
263
241
- def __init__ (self , execmodel , hasprimary = False ):
264
+ def __init__ (self , execmodel , hasprimary = False , size = None ):
242
265
""" by default allow unlimited number of spawns. """
243
266
self .execmodel = execmodel
244
267
self ._running_lock = self .execmodel .Lock ()
245
268
self ._running = set ()
246
269
self ._shuttingdown = False
247
270
self ._waitall_events = []
271
+ self ._semaphore = nullcontext () if size is None else self .execmodel .Semaphore (size )
248
272
if hasprimary :
249
273
if self .execmodel .backend != "thread" :
250
274
raise ValueError ("hasprimary=True requires thread model" )
@@ -307,7 +331,7 @@ def spawn(self, func, *args, **kwargs):
307
331
of the given func(*args, **kwargs).
308
332
"""
309
333
reply = Reply ((func , args , kwargs ), self .execmodel )
310
- with self ._running_lock :
334
+ with self ._semaphore , self . _running_lock :
311
335
if self ._shuttingdown :
312
336
raise ValueError ("pool is shutting down" )
313
337
self ._running .add (reply )
0 commit comments