apppublic/appPublic/thread_workers.py

34 lines
759 B
Python
Raw Normal View History

2021-07-27 01:12:49 +08:00
import time
import threading
import random
from appPublic.background import Background
class ThreadWorkers:
2022-02-08 12:27:23 +08:00
def __init__(self, max_workers=10):
self.semaphore = threading.Semaphore(value=max_workers)
2021-07-27 01:12:49 +08:00
self.co_worker = 0
def _do(self, func, *args, **kwargs):
2022-02-08 12:27:23 +08:00
self.semaphore.acquire()
2021-07-27 01:12:49 +08:00
self.co_worker += 1
func(*args, **kwargs)
self.co_worker -= 1
self.semaphore.release()
def do(self, func, *args, **kwargs):
b = Background(self._do, func, *args, **kwargs)
b.start()
def get_workers(self):
return self.co_worker
if __name__ == '__main__':
def k(worker):
t = random.randint(1,4)
print('current workers=',worker.get_workers(), 'sleep=', t)
time.sleep(t)
2022-02-08 12:27:23 +08:00
w = ThreadWorkers(max_workers=30)
2021-07-27 01:12:49 +08:00
for i in range(100000):
w.do(k, w)