Python高级培训第四次任务(寒假)

信号量

信号量:给定一个数据上锁,对多个线程可见,即信号量是用来控制线程并发数的(个人理解)

实例(即实现的过程)

import threading
import time


def run(n):
    semaphore.acquire()
    print(n)
    time.sleep(1)
    semaphore.release()



if __name__ == '__main__':
    semaphore = threading.Semaphore(5)
    for i in range(10):
        t = threading.Thread(target=run,args=(i,))
        t.start()

结果

0
1
2
3
4
65

7
89


Process finished with exit code 0

注释:前五个数0-4一并打印,后五个数紧接其后。

条件变量condition函数

  • acquire — 线程锁,注意线程条件变量 Condition 中的所有相关函数使用必须在acquire / release 内部操作;
  • release — 释放锁,注意线程条件变量 Condition 中的所有相关函数使用必须在acquire / release 内部操作;
  • wait( timeout ) 线程挂起(阻塞状态),直到收到一个 notify 通知或者超时才会被唤醒继续运行(超时参数默认不设置,可选填,类型是浮点数,单位是秒)。wait 必须在已获得 Lock 前提下才能调用,否则会触发 RuntimeError;
  • notify(n=1) — 通知其他线程,那些挂起的线程接到这个通知之后会开始运行,缺省参数,默认是通知一个正等待通知的线程,最多则唤醒 n 个等待的线程。 notify 必须在已获得 Lock 前提下才能调用,否则会触发 RuntimeError ,notify 不会主动释放 Lock ;
  • notifyAll — 如果 wait 状态线程比较多,notifyAll 的作用就是通知所有线程;
    实例
import threading
import time


def run(x):
    # 条件变量condition 线程上锁
1    con.acquire()
2   print(f"线程{x}")
3   con.notify()
4    print(f"线程{x}挂起")
5   con.wait()
    # time.sleep(1)
6    print(f"线程{x}再次启动")
    con.notify()
    con.release()

if __name__ == '__main__':
    # 创建条件变量condition
    con = threading.Condition()
    for i in range(10):
        t = threading.Thread(target=run,args=(i,))
        t.start()

结果

线程0
线程0挂起
线程1
线程1挂起
线程0再次启动
线程1再次启动
线程2
线程2挂起
线程3
线程3挂起
线程2再次启动
线程3再次启动
线程4
线程4挂起
线程5
线程5挂起
线程4再次启动
线程6
线程6挂起
线程5再次启动
线程7
线程7挂起
线程6再次启动
线程7再次启动
线程8
线程8挂起
线程9
线程9挂起
线程8再次启动
线程9再次启动

Process finished with exit code 0

注释:为了便于解释过程,在上面代码段添加了序号;线程0运行从1-5,运到con.wait()挂起,下一个线程运行到3时通知前面等待的线程运行,自己也运行con.wait()挂起。

事件对象

一个线程发出事件信号,而其他线程等待该信号。

一个事件对象管理一个内部标志,调用 set() 方法可将其设置为true,调用 clear() 方法可将其设置为false,调用 wait() 方法将进入阻塞直到标志为true。

实例

import threading
import time


def car():
    while True:
        if event.is_set():
            print('小车行驶')
        else:
            print('小车停止')
            event.wait()

def set_event():
    while True:
        event.set()
        time.sleep(1)
        event.clear()
        time.sleep(3)

if __name__ == '__main__':
    event = threading.Event()
    c1 = threading.Thread(target=car)
    c1.start()
    set_e = threading.Thread(target=set_event)
    set_e.start()

结果

小车停止
小车行驶
小车行驶
小车行驶
小车行驶
小车行驶
小车行驶
小车行驶
.
.
.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值