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实现石头剪刀布的具体代码,供大家参考,具体内容如下 概述: 如果你和我一样是一个有着其他语言基础的编程者,那我想这个小程序对于你来说是小case。由于本人...

Python基于ThreadingTCPServer创建多线程代理的方法示例

本文实例讲述了Python基于ThreadingTCPServer创建多线程代理的方法。分享给大家供大家参考,具体如下: #coding=utf8 from BaseHTTPServ...

原来我一直安装 Python 库的姿势都不对呀

平常我都是直接执行 pip install 安装的第三方库,很多教程也是这么介绍的,一直以来我都认为这是标准的、正确的安装 Python 第三方库的姿势。直到我最近看到Python核心开...

解决Python plt.savefig 保存图片时一片空白的问题

更新 这里我会列出对本文的更新。 2017 年 9 月 28 日:修正几处错字,优化排版。 问题 当使用如下代码保存使用 plt.savefig 保存生成的图片时,结果打开生成的图片却是...

python 中Arduino串口传输数据到电脑并保存至excel表格

python 中Arduino串口传输数据到电脑并保存至excel表格

起因:学校运河杯报了个项目,制作一个天气预测的装置。我用arduino跑了BME280模块,用蓝牙模块实现两块arduino主从机透传。但是为了分析,还需要提取出数据。因此我用pytho...