温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在python中使用condition多线程高级锁

发布时间:2021-05-07 16:00:44 来源:亿速云 阅读:179 作者:Leah 栏目:开发技术

怎么在python中使用condition多线程高级锁?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

python可以做什么

Python是一种编程语言,内置了许多有效的工具,Python几乎无所不能,该语言通俗易懂、容易入门、功能强大,在许多领域中都有广泛的应用,例如最热门的大数据分析,人工智能,Web开发等。

多线程编程中如果使用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:好嗒

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI