-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbounded_pool_executor.py
43 lines (28 loc) · 1.02 KB
/
bounded_pool_executor.py
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
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2019 [email protected]
#
import multiprocessing
import concurrent.futures
import threading
name = 'bounded_pool_executor'
class _BoundedPoolExecutor:
semaphore = None
def acquire(self):
self.semaphore.acquire()
def release(self, fn):
self.semaphore.release()
def submit(self, fn, *args, **kwargs):
self.acquire()
future = super().submit(fn, *args, **kwargs)
future.add_done_callback(self.release)
return future
class BoundedProcessPoolExecutor(_BoundedPoolExecutor, concurrent.futures.ProcessPoolExecutor):
def __init__(self, max_workers=None):
super().__init__(max_workers)
self.semaphore = multiprocessing.BoundedSemaphore(max_workers)
class BoundedThreadPoolExecutor(_BoundedPoolExecutor, concurrent.futures.ThreadPoolExecutor):
def __init__(self, max_workers=None):
super().__init__(max_workers)
self.semaphore = threading.BoundedSemaphore(max_workers)