python多线程同步:Event对象

1.python事件Event相关函数介绍

set() — 全局内置标志Flag,将标志Flag 设置为 True,通知在等待状态(wait)的线程恢复运行

isSet() — 获取标志Flag当前状态,返回True 或者 False

wait() — 一旦调用,线程将会处于阻塞状态,直到等待其他线程调用set()函数恢复运行

clear() — 将标志设置为False

2.python事件Event原理

事件event中有一个全局内置标志Flag,值为 True 或者False。使用wait()函数的线程会处于阻塞状态,此时Flag指为False,直到有其他线程调用set()函数让全局标志Flag置为True,其阻塞的线程立刻恢复运行,还可以用isSet()函数检查当前的Flag状态

3.要求

定义一个全局变量列表:test_list,创建两个函数(test_list_one和test_list_two)

test_list_one:for遍历10个数字添加到列表中,且没添加一个数字都要睡眠2秒钟

test_list_two: for遍历这个全局列表10次,每次都pop() 一个数字,每次pop()一次后睡眠1秒钟

最后,开启两个线程,先起 test_list_two() 最后起test_list_two()

4.没有event时

def test_list_one():
    print("--------test_list_one---------")
    for i in range(0,11):
        print("--------test_list_one---循环---%d" % i)
        test_list.append(1)
        time.sleep(1)
    print("--------test_list_one----结束")

def test_list_two():
    print("--------test_list_two---------")
    for i in range(0, 11):
        print("--------test_list_two---循环---%d" % i)
        test_list.pop()
        time.sleep(1)
    print("--------test_list_two----结束")

event = threading.Event()
event.clear()
test_list = list()

if __name__ == '__main__':
    threading.Thread(target=test_list_two, ).start()
    threading.Thread(target=test_list_one,).start()

结果是报错:应为此时线程无法控制,当一个函数被阻塞时,它会去执行其他没有阻塞的函数,应为pop()的时间比append()的时间短,所以会出现pop()空列表的情况,报错:

5.使用event时

def test_list_one():
    print("--------test_list_one---------")
    for i in range(0,11):
        print("--------test_list_one---循环---%d" % i)
        test_list.append(1)
        time.sleep(1)
    print("--------test_list_one----结束")
    event.set()

def test_list_two():
    print("--------test_list_two---------")
    event.wait()
    for i in range(0, 11):
        print("--------test_list_two---循环---%d" % i)
        test_list.pop()
        time.sleep(1)
    print("--------test_list_two----结束")

event = threading.Event()
event.clear()
test_list = list()

if __name__ == '__main__':
    threading.Thread(target=test_list_two, ).start()
    threading.Thread(target=test_list_one,).start()

注意:event.clear(), event.wait(),event.set() 的作用,第1部分有

结果:时按照线程同步执行

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

奔跑的蜗牛..

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值