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

yipeiwu_com6年前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高级用法总结

列表推导(list comprehensions) 场景1:将一个三维列表中所有一维数据为a的元素合并,组成新的二维列表。 最简单的方法:新建列表,遍历原三维列表,判断一维数据是否为a,...

django框架model orM使用字典作为参数,保存数据的方法分析

本文实例讲述了django框架model orM使用字典作为参数,保存数据的方法。分享给大家供大家参考,具体如下: 假设有一个字典,里面已经有了所有相关信息,现在想利用这个字典作为参数,...

django 将model转换为字典的方法示例

平常的开发过程中不免遇到需要把model转成字典的需求,尤其是现在流行前后端分离架构,Json格式几乎成了前后端之间数据交换的标准,这种model转dict的需求就更多了,本文介绍日常使...

python字典的常用方法总结

python字典的常用方法总结

python中字典是非常常用的数据类型,了解各种方法的作用及优缺点对于字典的使用非常有用。 dict.clear() 的方法用于清空所有的键值对,清空后字典变成空字典。代码示例如下:...

Python序列类型的打包和解包实例

打包 如给出一系列由逗号分隔的表达式,他们将被视为一个单独元组,即使没有提供封闭的圆括号 如: numbers = 1, 2, 3, 4 使numbers被赋值元组(1, 2, 3...