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调用新浪微博API项目实践

python调用新浪微博API项目实践

因为最近接触到调用新浪微博开放接口的项目,所以就想试试用python调用微博API。 SDK下载地址:http://open.weibo.com/wiki/SDK 代码不多十几K,完全可...

如何在Python函数执行前后增加额外的行为

首先来看一个小程序,这个是计量所花费时间的程序,以下是以往的解决示例 from functools import wraps, partial from time import ti...

Python 支持向量机分类器的实现

支持向量机(Support Vector Machine, SVM)是一类按监督学习(supervised learning)方式对数据进行二元分类的广义线性分类器(generalize...

Python使用psutil获取进程信息的例子

psutil是什么 psutil是一个能够获取系统信息(包括进程、CPU、内存、磁盘、网络等)的Python模块。主要用来做系统监控,性能分析,进程管理,像glances也是基于psut...

python下os模块强大的重命名方法renames详解

python下os模块强大的重命名方法renames详解  在python中有很多强大的模块,其中我们经常要使用的就是OS模块,OS模块提供了超过200个方法来供我们使用,并且...