Python之多线程编程5,线程同步之Semaphore(线程数量控制)

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对象开始和释放位置要注意,一般开始为线程开始运行的语句,结束为运行方法结束的语句。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值