python多线程高级锁condition简单用法示例

yipeiwu_com6年前Python基础

本文实例讲述了python多线程高级锁condition简单用法。分享给大家供大家参考,具体如下:

多线程编程中如果使用Condition对象代替lock, 能够实现在某个事件触发后才处理数据, condition中含有的方法:

  • - wait:线程挂起,收到notify通知后继续运行
  • - notify:通知其他线程, 解除其它线程的wai状态
  • - notifyAll(): 通知所有线程
  • - acquire和release: 获得锁和解除锁, 与lock类似,
  • - enter和exit使得对象支持上下文操作:
  def __enter__(self):
    return self._lock.__enter__()
  def __exit__(self, *args):
    return self._lock.__exit__(*args)

代码:

import threading
from threading import Condition
# condition
class XiaoAi(threading.Thread):
  def __init__(self, cond):
    self.cond = cond
    super().__init__(name="xiaoai")
  def run(self):
    self.cond.acquire()
    self.cond.wait()
    print('{}:ennn. '.format(self.name))
    self.cond.notify()
    self.cond.wait()
    print('{}:好嗒. '.format(self.name))
    self.cond.release()
class TianMao(threading.Thread):
  def __init__(self, cond):
    super().__init__(name="tiaomao")
    self.cond = cond
  def run(self):
    self.cond.acquire()
    print('{}:hello ~ xiaoai. '.format(self.name))
    self.cond.notify()
    self.cond.wait()
    print('{}:我们来念一首诗吧! . '.format(self.name))
    self.cond.notify()
    self.cond.release()
if __name__ == '__main__':
  condition = Condition()
  xiaoai = XiaoAi(condition)
  tianmao = TianMao(condition)
  # 启动顺序很重要
  xiaoai.start()
  tianmao.start()

打印结果:

tiaomao:hello ~ xiaoai.
xiaoai:ennn.
tiaomao:我们来念一首诗吧! .
xiaoai:好嗒

总结:

这个比较鸡肋

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python进程与线程操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》、《Python+MySQL数据库程序设计入门教程》及《Python常见数据库操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

python创建n行m列数组示例

我就废话不多说了,直接上代码吧! >>> matrix=[None]*2 >>> print(matrix) [None, None] >&...

python使用zip将list转为json的方法

zip()函数将可迭代对象作为参数,并打包成元组,返回的是一个个zip对象,可以使用list或dict转换返回结果,使用*zip可以将打包的对象分解成列表 >>>...

Python类和对象的定义与实际应用案例分析

Python类和对象的定义与实际应用案例分析

本文实例讲述了Python类和对象的定义与实际应用。分享给大家供大家参考,具体如下: 1.DVD管理系统 # -*- coding:utf-8 -*- #! python3 clas...

使用Python的Turtle库绘制森林的实例

使用Python的Turtle库绘制森林的实例

这是由一个小作业引发的对Python的Turtle库的学习 下面是官方手册: Turtle官方手册 1.配置编程环境 由于现在的笔记本是临时借的,编程环境不是熟悉的环境,又由于种种原因...

Python字典简介以及用法详解

Python字典简介以及用法详解

#!/usr/bin/env python # -*- coding:utf-8 -*- """ 老规矩以下方法环境2.7.x,请3.x以上版本的朋友记得格式print(输出内...