【python】关于控制线程运行的数量

【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))
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值