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生成树形图案的具体代码,供大家参考,具体内容如下 先看一下效果,见下图。 上面这颗大树是使用Python + Tkinter绘制的,主要原理为使用分形画...

Python中的 enum 模块源码详析

起步 上一篇 《Python 的枚举类型》 文末说有机会的话可以看看它的源码。那就来读一读,看看枚举的几个重要的特性是如何实现的。 要想阅读这部分,需要对元类编程有所了解。 成员名不允...

浅谈python3.6的tkinter运行问题

python3.6在运行tkinter时要选择 run as Python unit-test, 否则报错 ModuleNotFoundError: No module named 't...

python简单操作excle的方法

Python操作Excle文件:使用xlwt库将数据写入Excel表格,使用xlrd 库从Excel读取数据。 从excle读取数据存入数据库 1、导入模块: import xlrd...

python程序中的线程操作 concurrent模块使用详解

一、concurrent模块的介绍 concurrent.futures模块提供了高度封装的异步调用接口 ThreadPoolExecutor:线程池,提供异步调用 ProcessPo...