在python中监控线程同步 [英] Monitor thread synchronization in python

查看:38
本文介绍了在python中监控线程同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有什么办法可以像java方法同步一样在python类中使用monitor线程同步来保证线程安全和避免竞争条件?

我想要一个类似监视器的同步机制,它只允许在我的类或对象中调用一个方法

解决方案

你可能想看看 python 线程接口.对于简单的互斥功能,您可以使用 Lock 对象.您可以使用 with 语句轻松完成此操作,例如:

<代码>...锁 = 锁()...与(锁定):# 这段代码一次只会被一个线程执行# 当线程退出'with'块时,锁被释放...

另请参阅此处,了解 Python 中不同线程同步机制的概述.>

Java 的 synchronized 没有 python 语言构造(但我想它可以使用装饰器构建)

Is there any way to use monitor thread synchronization like java methods synchronization,in python class to ensure thread safety and avoid race condition?

I want a monitor like synchronization mechanism that allows only one method call in my class or object

解决方案

You might want to have a look at python threading interface. For simple mutual exclusion functionality you might use a Lock object. You can easily do this using the with statement like:

...
lock = Lock()
...
with (lock):
  # This code will only be executed by one single thread at a time
  # the lock is released when the thread exits the 'with' block
  ...

See also here for an overview of different thread synchronization mechanisms in python.

There is no python language construct for Java's synchronized (but I guess it could be built using decorators)

这篇关于在python中监控线程同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆