参考链接
https://www.liaoxuefeng.com/wiki/1016959663602400/1017629247922688
代码

#! -*-coding: utf-8-*-

import threading
import time

class test(threading.Thread): #继承threading类
def __init__(self, i, sem):
super(test, self).__init__() #继承python的构造方法,这为python2的写法,python3可直接super().__init__()
self.i = i
self.sem = sem

def run(self):
print("the test i is : {} {} ".format(str(self.i), time.time()))
x = 0
while True:
x = x ^ 1
self.sem.release() #释放线程数,线程数加1

if __name__ == '__main__':
sem = threading.Semaphore(2) #设置可同时执行的最大线程数
for i in range(50):
sem.acquire() #获得线程,可用线程数减1
t = test(i, sem) #给执行函数传递值
t.start() #执行函数

>PS: 使用python2执行时耗费CPU资源较大,并且`ctrl+c`无法结束进程,只能通过`kill -9`命令,python3命令执行会节省更多CPU资源,基本能节省30%~50%,可通过`ctrl+c`结束进程


Thank you for using 苹果树. | 粤ICP备18042975号-1