【python】关于控制线程运行的数量
说明
这只是一个我自己使用的一个控制线程数目的方式,便于以后使用时拿出来翻阅查看使用。
代码
import threading
from time import sleep,ctime
from apply import apply
loops = [4, 2, 8, 9, 1, 3, 5, 6, 3, 7, 8, 9, 4, 1, 2, 5, 6, 7, 4, 6]
def loop(nloop, nsec):
print('start loop',nloop,'at:',ctime())
sleep(nsec)
print('loop',nloop,'done at:',ctime())
return 1
class MyThread(threading.Thread):
def __init__(self,func,args):
super().__init__()
self.func = func
self.args = args
def run(self):
with thread_max_num:
apply(self.func,self.args)
if __name__=='__main__':
begin=ctime()
print('starting at:',ctime())
num = 3
thread = []
thread_max_num = threading.Semaphore(num)
nloops = range(len(loops))
for i in nloops:
t=MyThread(func=loop,args=(i,loops[i]))
thread.append(t)
for i in nloops:
thread[i].start()
for i in nloops:
thread[i].join()
end=ctime()
print('starting at:', begin)
print('all done at:',end)
print(sum(loops))