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内置数据类型详解

通常来说Python在编程语言中的定位为脚本语言——scripting language 高阶动态编程语言。 Python是以数据为主,变量的值改变是指变量去指到一个地址。 即:Id(变...

pandas实现to_sql将DataFrame保存到数据库中

pandas实现to_sql将DataFrame保存到数据库中

目的 在数据分析时,我们有中间结果,或者最终的结果,需要保存到数据库中;或者我们有一个中间的结果,如果放到数据库中通过sql操作会更加的直观,处理后再将结果读取到DataFrame中。...

Python 3.6 -win64环境安装PIL模块的教程

Python 3.6 -win64环境安装PIL模块的教程

PIL:Python Imaging Library,已经是Python平台事实上的图像处理标准库了。PIL功能非常强大,但API却非常简单易用。 由于PIL仅支持到Python 2.7...

python备份文件以及mysql数据库的脚本代码

复制代码 代码如下: #!/usr/local/python import os import time import string source=['/var/www/html/xxx...

python实现合并两个数组的方法

本文实例讲述了python实现合并两个数组的方法。分享给大家供大家参考。具体如下: python合并两个数组,将两个数组连接成一个数组,例如,数组 a=[1,2,3] ,数组 b=[4,...