@@ -64,8 +64,29 @@ def reraise(cls, val, tb):
64
64
# def log_extra(*msg):
65
65
# f.write(" ".join([str(x) for x in msg]) + "\n")
66
66
67
+ if sys .version_info >= (3 , 7 ):
68
+ from contextlib import nullcontext
69
+ else :
70
+ class nullcontext (object ):
71
+ """Context manager that does no additional processing.
72
+ Used as a stand-in for a normal context manager, when a particular
73
+ block of code is only sometimes used with a normal context manager:
74
+ cm = optional_cm if condition else nullcontext()
75
+ with cm:
76
+ # Perform operation, using optional_cm if condition is True
77
+ """
78
+
79
+ def __init__ (self , enter_result = None ):
80
+ self .enter_result = enter_result
81
+
82
+ def __enter__ (self ):
83
+ return self .enter_result
67
84
68
- class EmptySemaphore :
85
+ def __exit__ (self , * excinfo ):
86
+ pass
87
+
88
+
89
+ class EmptySemaphore (nullcontext ):
69
90
acquire = release = lambda self : None
70
91
71
92
@@ -238,13 +259,14 @@ class WorkerPool(object):
238
259
when the pool received a trigger_shutdown().
239
260
"""
240
261
241
- def __init__ (self , execmodel , hasprimary = False ):
262
+ def __init__ (self , execmodel , hasprimary = False , size = None ):
242
263
""" by default allow unlimited number of spawns. """
243
264
self .execmodel = execmodel
244
265
self ._running_lock = self .execmodel .Lock ()
245
266
self ._running = set ()
246
267
self ._shuttingdown = False
247
268
self ._waitall_events = []
269
+ self ._semaphore = self .execmodel .Semaphore (size )
248
270
if hasprimary :
249
271
if self .execmodel .backend != "thread" :
250
272
raise ValueError ("hasprimary=True requires thread model" )
@@ -307,7 +329,7 @@ def spawn(self, func, *args, **kwargs):
307
329
of the given func(*args, **kwargs).
308
330
"""
309
331
reply = Reply ((func , args , kwargs ), self .execmodel )
310
- with self ._running_lock :
332
+ with self ._semaphore , self . _running_lock :
311
333
if self ._shuttingdown :
312
334
raise ValueError ("pool is shutting down" )
313
335
self ._running .add (reply )
0 commit comments