Warm tip: This article is reproduced from serverfault.com, please click

其他-在python中监视线程同步

(其他 - Monitor thread synchronization in python)

发布于 2012-07-04 19:20:04

有什么方法可以在python类中使用监视器线程同步(如java方法同步)来确保线程安全并避免竞争条件?

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

Questioner
Pooya
Viewed
11
MartinStettner 2012-07-05 03:38:53

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

...
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
  ...

另请参见此处,以了解python中不同线程同步机制的概述。

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