Event

一个线程需要根据另外一个线程的状态来确定自己的下一步操作,需要调用threading库中Event对象;Event包含一个可由线程设置的信号标志,在初始情况下,event对象的标志位为假(false);。如果一个线程等待一个event对象,而这个event对象标志为假,那么这个线程将会被一直阻塞到标志为真(true);。

同理:一个线程如果将一个event对象的信号标志设置为真,它将唤醒所有等待这个event对象的线程。

如果一个线程等待一个已经被设置为真的event对象,那么它将忽略这个事件,继续执行。

#!/usr/bin/env python
# encoding: utf-8
"""
@author: 侠之大者kamil
@file: Event_test.py
@time: 2016/3/23 9:42
"""
from threading import Thread ,Event
import time
def countdown(n,started_evt):
print('countdown starting',time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))
started_evt.set()
while n >0:
print("T-time_kamil:",n)
n -=1
time.sleep(2)
started_evt = Event()
print("Launching countdown",time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))
t = Thread(target=countdown,args=(5,started_evt))
t.start()
started_evt.wait()
print("countdown is running",time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))

结果:

C:\Python34\python.exe D:/kamil/Documents/py/process/Event_test.py
Launching countdown 2016-03-23 16:03:28
countdown starting 2016-03-23 16:03:28
T-time_kamil: 5
countdown is running 2016-03-23 16:03:28
T-time_kamil: 4
T-time_kamil: 3
T-time_kamil: 2
T-time_kamil: 1 Process finished with exit code 0

Condition

如果一个线程需要不停重复的使用event对象,最好使用condition对象实现一个周期定时器,每当定时器超时的时候,其他线程都可以检测到:

#!/usr/bin/env python
# encoding: utf-8
"""
@author: 侠之大者kamil
@file: event_test2.py
@time: 2016/3/23 14:45
"""
import time,threading
class PeriodicTimer:
def __init__(self,interval):
self._interval = interval
self._flag = 0
self._cv = threading.Condition()#使用Condition对象可以在某些事件触发或者达到特定的条件后才处理数据 def start(self):
t = threading.Thread(target=self.run)
t.daemon = True#Daemon线程表明整个Python主程序只有在Daemon子线程运行时可以退出.
t.start()
def run(self):
while True:
time.sleep(self._interval)
with self._cv:
self._flag ^=1
self._cv.notify_all()
def wait_for_tick(self):
with self._cv:
last_flag = self._flag
while last_flag == self._flag:
self._cv.wait()
ptimer = PeriodicTimer(5)
ptimer.start() def countdown(nticks):
while nticks > 0 :
ptimer.wait_for_tick()
print("t_time",nticks)
nticks -= 1
def countup(last):
n = 0
while n < last:
ptimer.wait_for_tick()
print("counting",n)
n +=1 threading.Thread(target=countdown,args=(6,)).start()
threading.Thread(target=countup,args=(3,)).start()

结果:

C:\Python34\python.exe D:/kamil/Documents/py/process/event_test2.py
t_time 6
counting 0
t_time 5
counting 1
t_time 4
counting 2
t_time 3
t_time 2
t_time 1 Process finished with exit code 0

如上文中event在为真后,所有等待的进程都要开始,如果只想唤起一个进程,那可以使用Condition 对象来替代

Event&Condition pyton的更多相关文章

  1. 扯扯python的多线程的同步锁 Lock RLock Semaphore Event Condition

    我想大家都知道python的gil限制,记得刚玩python那会,知道了有pypy和Cpython这样的解释器,当时听说是很猛,也就意味肯定是突破了gil的限制,最后经过多方面测试才知道,还是那德行… ...

  2. python 多线程中的同步锁 Lock Rlock Semaphore Event Conditio

    摘要:在使用多线程的应用下,如何保证线程安全,以及线程之间的同步,或者访问共享变量等问题是十分棘手的问题,也是使用多线程下面临的问题,如果处理不好,会带来较严重的后果,使用python多线程中提供Lo ...

  3. 1Z0-053 争议题目解析697

    1Z0-053 争议题目解析697 考试科目:1Z0-053 题库版本:V13.02 题库中原题为: 697.Which statement is true about a Scheduler-gen ...

  4. Python-09-线程、进程、协程、异步IO

    0. 什么是线程(thread)? 线程,有时被称为轻量级进程(Lightweight Process,LWP),是程序执行流的最小单元.一个标准的线程由线程ID,当前指令指针(PC),寄存器集合和堆 ...

  5. Python Day10

    进程 在python中multiprocess模块提供了Process类,实现进程相关的功能.但是,由于它是基于fork机制的,因此不被windows平台支持.想要在windows中运行,必须使用if ...

  6. AngularJS 分页

    前端源码: <div> <h1>列表页33</h1> <table> <thead> <tr><td>CandiID ...

  7. python学习笔记12 ----线程、进程

    进程和线程的概念 进程和线程是操作系统中两个很重要的概念,对于一般的程序,可能有若干个进程,每一个进程有若干个同时执行的线程.进程是资源管理的最小单位,线程是程序执行的最小单位(线程可共享同一进程里的 ...

  8. Python之线程、进程和协程

    python之线程.进程和协程 目录: 引言 一.线程 1.1 普通的多线程 1.2 自定义线程类 1.3 线程锁 1.3.1 未使用锁 1.3.2 普通锁Lock和RLock 1.3.3 信号量(S ...

  9. Python_进程、线程及协程

    一.Python进程 IO密集型----多线程 计算密集型----多进程 1.单进程 from multiprocessing import Process def foo(i): print('你好 ...

随机推荐

  1. Oracle 多表update

    今天凌晨因为要在数据库里做一些操作,是关于两表关联的update,但语句怎么写都不正确,老是报错,于是心惊肉跳(就怕不能及时完成操作)去查了一下,NND,原来把SQL写成了在SQL Server下面的 ...

  2. nginx反向代理tomcat访问时浏览器加载失败,出现 ERR_CONTENT_LENGTH_MISMATCH 问题

    问题说明:测试机上部署了一套业务环境,nginx反向代理tomcat,在访问时长时间处于加载中,十分缓慢! 通过浏览器调试(F12键->Console),发现有错误ERR_CONTENT_LEN ...

  3. 处理OSX创建的U盘, 删除EFI分区

    1. 运行 diskpart 2. list disk 3. 根据列出的硬盘, select disk [编号] 4. clean 5. exit 然后再创建分区和格式化

  4. php常见问题以及解决方法

    在使用php的过程中,经常会出现一些问题,下面是我遇到的一些问题以及解决方法 1,乱码问题,中文乱码问题 原因是:编码方式不一样,有UTF-8,gbk-2312等编码方式,不同的编码方式导致浏览器在解 ...

  5. C#加密解密大全

    1.方法一 (不可逆加密)     public string EncryptPassword(string PasswordString,string PasswordFormat )      { ...

  6. 图片加载框架Picasso解析

    picasso是Square公司开源的一个Android图形缓存库 主要有以下一些特性: 在adapter中回收和取消当前的下载: 使用最少的内存完成复杂的图形转换操作: 自动的内存和硬盘缓存: 图形 ...

  7. Java 生成 UUID

    1.UUID 简介 UUID含义是通用唯一识别码 (Universally Unique Identifier),这是一个软件建构的标准,也是被开源软件基金会 (Open Software Found ...

  8. 前端手札--meta标记篇

    通用类: 声明编码 <meta charset='utf-8' /> SEO页面关键词 <meta name="keywords" content="y ...

  9. FileShare枚举的使用(文件读写锁)

    开发过程中,我们往往需要大量与文件交互,但往往会出现很多令人措手不及的意外,所以对普通的C#文件操作做了一次总结,问题大部分如下: 1:写入一些内容到某个文件中,在另一个进程/线程/后续操作中要读取文 ...

  10. ElasticSearch入门系列(二)交互API

    一.基于HTTP协议,以JSON为数据交互格式的RESTful API 向ElasticSearch发出请求的组成部分与其他的普通的HTTP请求是一样的: curl -X<VERB> '& ...