例如,我正在制作一个异步装饰器,并希望限制并发线程的数量:
from multiprocessing import cpu_count
from threading import Thread
class async:
def __init__(self, function):
self.func = function
self.max_threads = cpu_count()
self.current_threads = []
def __call__(self, *args, **kwargs):
func_thread = Thread(target = self.func, args = args, kwargs = kwargs)
func_thread.start()
self.current_threads.append(func_thread)
while len(self.current_threads) > self.max_threads:
self.current_threads = [t for t in self.current_threads if t.isAlive()]
from time import sleep
@async
def printA():
sleep(1)
print "A"
@async
def printB():
sleep(1)
print "B"
这是否会限制总并发线程数? IE浏览器。如果我有8个内核,由于存在两个独立的异步对象,当前代码最终会有16个以上的线程吗?
如果是这样,我该如何解决? 谢谢!