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基础之变量基本用法与进阶详解

Python基础之变量基本用法与进阶详解

本文实例讲述了Python基础之变量基本用法与进阶。分享给大家供大家参考,具体如下: 目标 变量的引用 可变和不可变类型 局部变量和全局变量 01. 变量的引用 变...

python实现发送form-data数据的方法详解

python实现发送form-data数据的方法详解

本文实例讲述了python实现发送form-data数据的方法。分享给大家供大家参考,具体如下: 源代码 -----------------------------2793612435...

win10系统下python3安装及pip换源和使用教程

win10系统下python3安装及pip换源和使用教程

一、python3的安装 建议安装python3,python2在未来将不再维护。 python官方下载地址 https://www.python.org/downloads/windo...

Python数据类型详解(一)字符串

一.基本数据类型   整数:int   字符串:str(注:\t等于一个tab键)   布尔值: bool   列表:list   列表用[]   元祖:tuple   元祖用()...

python实用代码片段收集贴

获取一个类的所有子类 复制代码 代码如下: def itersubclasses(cls, _seen=None):     """Generator ov...