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 简单搭建阻塞式单进程,多进程,多线程服务的实例

我们可以通过这样子的方式去理解apache的工作原理 1 单进程TCP服务(堵塞式) 这是最原始的服务,也就是说只能处理个客户端的连接,等当前客户端关闭后,才能处理下个客户端,是属于阻塞...

python中的&&及||的实现示例

首先说明一下,在python中是没有&&及||这两个运算符的,取而代之的是英文and和or。其他运算符没有变动。 接着重点要说明的是python中的a.any(),我之所以会涉及到这个函...

python flask解析json数据不完整的解决方法

当使用Python的flask框架来开发网站后台,解析前端Post来的数据,通常都会使用request.form来获取前端传过来的数据,但是如果传过来的数据比较复杂,其中右array,而...

python实现逻辑回归的方法示例

python实现逻辑回归的方法示例

本文实现的原理很简单,优化方法是用的梯度下降。后面有测试结果。 先来看看实现的示例代码: # coding=utf-8 from math import exp import ma...

分析用Python脚本关闭文件操作的机制

如果不用“with”,那么Python会在何时关闭文件呢?答案是:视情况而定。 Python程序员最初学到的东西里有一点就是可以通过迭代法很容易地遍历一个打开文件的全文: f =...