1

Suppose I need to do the following:

global_lock.acquire()
local_lock = threading.Lock()
local_lock.acquire()
register_local_lock(local_lock, some_associated_data)
global_lock.release()
do_some_work()
local_lock.release()

Q: How can I achieve the same thing using with statement?

P.S. In my application, there actually exist a workaround that separates the two lock acquisition. However, I think there could be senarios where the two lock acquisition must stay interleaved, so I'm still posting, with an additional question:

Q: Can all interleaved lock acquisition be eliminated by refactoring?

Huazuo Gao
  • 1,603
  • 14
  • 20
  • This example could use some improvement. Are you sharing `local_lock` between threads? As you wrote this code it's not clear `local_lock` is necessary. Also, is it necessary to hold `global_lock` while calling `register_local_lock `? If so, please make it clear that it is in your question. – alexgolec Sep 22 '15 at 16:31
  • @Alex I did get rid of interleaved lock acquisition in my application. I just wander if there are situations where no suitable workaround exists. – Huazuo Gao Sep 23 '15 at 00:08

1 Answers1

0

Q2: Yes, all interleaving can be eliminated. See any text on operating systems. This goes back to Per Brink Hansen's seminal work and the "banker's problem". If you mis-handle interleaved lock acquisition in any way, you can leave your system deadlocked.

In this case, it looks to me as if the only protection global_lock gives is where you access the handle to threading.lock. Is this actually necessary? Note that local_lock protects the rest of the critical region.

Q1: See Python Conditional "With" Lock Design

Community
  • 1
  • 1
Prune
  • 76,765
  • 14
  • 60
  • 81
  • In my example there is no risk of deadlock, so banker's algorithm is not likely to be helpful. Additionally, I want to eliminate this situation in python code, so that `with` statement can be used instead of `acquire()` `release()`. Sorry I didn't make it clear in my question. – Huazuo Gao Sep 23 '15 at 00:24
  • I'm glad to hear that you have no deadlock danger. Did the link for Q1 solve the other question for you? – Prune Sep 23 '15 at 00:26
  • Unfortunately not. It is a different question, in which there is only one lock. For my question, because the locked period of the two locks interleaves, their `with` statement scope must also interleave, which is impossible in python grammar. – Huazuo Gao Sep 23 '15 at 00:35
  • I see. No, if the scope overlaps, then you cannot do this with *two* "with" statements. You would have to eliminate the interleave and nest the "with" statements. – Prune Sep 23 '15 at 00:38