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内置变量-reversed(seq)

1、简单解释就是:反转一个序列对象 例子1: def fun3(): x = [3,6,9] for i in reversed(x): print(i,end=',')...

对Python3中dict.keys()转换成list类型的方法详解

对Python3中dict.keys()转换成list类型的方法详解

在python3中使用dict.keys()返回的不在是list类型了,也不支持索引,我们可以看一下下面这张图片 那么我们应该怎么办呢,其实解决的方法也是非常简单的,只需要使用list...

利用Python实现在同一网络中的本地文件共享方法

本文利用Python3启动简单的HTTP服务器,以实现在同一网络中共享本地文件。 启动HTTP服务器 打开终端,转入目标文件所在文件夹,键入以下命令: $ cd /Users/zer...

Python编程中使用Pillow来处理图像的基础教程

安装 刚接触Pillow的朋友先来看一下Pillow的安装方法,在这里我们以Mac OS环境为例: (1)、使用 pip 安装 Python 库。pip 是 Python 的包管理工具,...