python基于event实现线程间通信控制

yipeiwu_com5年前Python基础

这篇文章主要介绍了python基于event实现线程间通信控制,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

import threading,time
class Boss(threading.Thread):
  def run(self):
    print("We must work today!")
    event.isSet() or event.set()
    time.sleep(5)
    print("You can go home right now!")
    event.isSet() or event.set()

class Worker(threading.Thread):
  def run(self):
    event.wait()
    print("Oh,my god!!!")
    time.sleep(1)
    event.clear()
    event.wait()
    print("Oh,yeah!!!")
if __name__ == "__main__":
  event = threading.Event()
  threads = []
  for i in range(5):
    threads.append(Worker())
  threads.append(Boss())
  for t in threads:
    t.start()
  for t in threads:
    t.join()

运行后显示:

We must work today!
Oh,my god!!!
Oh,my god!!!
Oh,my god!!!
Oh,my god!!!
Oh,my god!!!
You can go home right now!
Oh,yeah!!!
Oh,yeah!!!
Oh,yeah!!!
Oh,yeah!!!
Oh,yeah!!!

Process finished with exit code 0

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python selenium 获取标签的属性值、内容、状态方法

获取标签内容 使用element.attribute()方法获取dom元素的内容,如: dr = driver.find_element_by_id('tooltip') dr.ge...

django1.11.1 models 数据库同步方法

在django1.9之前,数据库同步只需要一条命令:python manage.py syncdb 在djang1.9以后,数据库同步执行指令如下: 同步数据库接口(注意需要切换至pyt...

python复制文件到指定目录的实例

周末出去爬山,照了一大堆照片回来,照片同时存储为jpg和DNG格式,我用adobe bridge将dng格式的照片中要保留的筛选出来后,就不想再对着一张张去挑jpg的照片了,于是用pyt...

Pytorch 实现权重初始化

在TensorFlow中,权重的初始化主要是在声明张量的时候进行的。 而PyTorch则提供了另一种方法:首先应该声明张量,然后修改张量的权重。通过调用torch.nn.init包中的多...

Python魔法方法详解

据说,Python 的对象天生拥有一些神奇的方法,它们总被双下划线所包围,他们是面向对象的 Python 的一切。 他们是可以给你的类增加魔力的特殊方法,如果你的对象实现(重载)了这些方...