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的debug实用工具 pdb详解

叨逼叨 首先,介绍一下 pdb 调试,pdb 是 python 的一个内置模块,用于命令行来调试 Python 代码。或许你会说,现在用 Pycharm 等编辑器来调试代码很方便,为啥要...

Python PyInstaller安装和使用教程详解

Pyinstaller这个库是我用pip下载的第一个模块。接下来通过本文给大家分享Python PyInstaller安装和使用教程,一起看看吧。 安装 PyInstalle Pytho...

python的pandas工具包,保存.csv文件时不要表头的实例

用pandas处理.csv文件时,有时我们希望保存的.csv文件没有表头,于是我去看了DataFrame.to_csv的document。 发现只需要再添加header=None这个参数...

python3获取文件中url内容并下载代码实例

这篇文章主要介绍了python3获取文件中url内容并下载代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 #!/usr/b...

Python素数检测实例分析

本文实例讲述了Python素数检测的方法。分享给大家供大家参考。具体如下: 该程序实现了素数检测器功能,如果结果是true,则是素数,如果结果是false,则不是素数。 def fn...