Python之多线程编程5,线程同步之Semaphore(线程数量控制)
函数库的导入
from threading
import time
函数的调用
#arg默认参数为可同时运行的线程数
sem=threading.Semaphore(arg)
方法函数的建立
#调用本函来循环20次,每次多条线程进行,线程数为Semaphore的参数
class twoclass(threading.Thread):
def __init__(self, sem):
super().__init__()
self._sem = sem
def run(self):
for i in range(10):
#sem对象获取线程
sem.acquire()
new_thread = oneclass(f"这是第{i}个数值", self._sem)
new_thread.start()
#调用函数类,实现每隔一秒打印一句话
class oneclass(threading.Thread):
def __init__(self, arg1, sem):
super().__init__()
self.args = arg1
self._sem = sem
def run(self):
a = time.time()
time.sleep(1)
print(self.args, end=",")
print(f"constant time:{time.time() - a}")
#sem对象释放线程
self._sem.release()
主函数的实现
if __name__ == "__main__":
sem = threading.Semaphore(2)
thread = twoclass(sem)
thread.start()
运行结果(因为系统的原因,运行结果不唯一):
总结:
Semaphore主要用于控制线程,当参数为1时,类似于锁的Lock()函数。
Semaphore对象开始和释放位置要注意,一般开始为线程开始运行的语句,结束为运行方法结束的语句。