Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
480 views
in Technique[技术] by (71.8m points)

locking - Python Conditional "With" Lock Design

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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'

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...