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中tkinter的应用:修改字体的实例讲解

python中tkinter的应用:修改字体的实例讲解

参考链接:tkinter book font字体的参数有如下6个 family: 字体类别,如'Fixdsys' size: 作为一个整数,以点字体的高度。为了获得字体的n个像素高,使用...

python下PyGame的下载与安装过程及遇到问题

1.去官网下载PyGame    注意:要下载对应版本的包    官网地址:http://www.pygame.org/download.shtm...

kaggle+mnist实现手写字体识别

现在的许多手写字体识别代码都是基于已有的mnist手写字体数据集进行的,而kaggle需要用到网站上给出的数据集并生成测试集的输出用于提交。这里选择keras搭建卷积网络进行识别,可以直...

Django 创建新App及其常用命令的实现方法

创建新的项目 django-admin.py startproject my_project 创建新的App # 在Django项目(my_project)的根目录下执行 py...

Python实现分割文件及合并文件的方法

本文实例讲述了Python实现分割文件及合并文件的方法。分享给大家供大家参考。具体如下: 分割文件split.py如下: #!/usr/bin/python ############...