Python条件“与"锁设计 [英] Python Conditional "With" Lock Design

查看:51
本文介绍了Python条件“与"锁设计的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用with语句进行一些共享锁定

I am trying to do some shared locking using with statements

def someMethod(self, hasLock = False):
     with self.my_lock:
         self.somethingElse(hasLock=True)


def somethingElse(self, hasLock = False):
    #I want this to be conditional...
    with self.my_lock:
          print 'i hate hello worlds"

那有意义吗?我基本上只想在没有锁的情况下使用.

That make sense? I basically only want to do the with if I don't already have the lock.

除了能够做到这一点之外,这是一个糟糕的设计吗?我应该只是获取/释放自己吗?

On top of being able to accomplish this, is it a bad design? Should I just acquire/release myself?

推荐答案

只需使用可重复输入的threading.RLock,这意味着它可以被同一线程多次获取.

Just use a threading.RLock which is re-entrant meaning it can be acquired multiple times by the same thread.

http://docs.python.org/library/threading.html#rlock-objects

为清楚起见,在with语句中使用RLock,就像在示例代码中一样:

For clarity, the RLock is used in the with statements, just like in your sample code:

lock = threading.RLock()

def func1():
    with lock:
        func2()

def func2():
    with lock: # this does not block even though the lock is acquired already
        print 'hello world'

至于这是否是错误的设计,我们需要更多的上下文.为什么两个功能都需要获取锁?什么时候func2func1以外的其他东西调用?

As far as whether or not this is bad design, we'd need more context. Why both of the functions need to acquire the lock? When is func2 called by something other than func1?

这篇关于Python条件“与"锁设计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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