How do I know if a Python.Lock multiprocessor is released or not?

>>> l = Lock()
>>> l.acquire()
True
>>> l.release()
>>> l.release()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: semaphore or lock released too many times

throws a ValueError exception. How can I prevent a lock from being released more than once? Something like l.is_released ()?

+3
source share
3 answers

The question is a bit unclear. You need to use semaphores instead of locks or check lock lock.

Python locks are not the same as .Net locks, for example. Python Lock unlocks releases ALL other threads that have acquired () on the same lock and are currently locked. Any stream can be freed, and everything goes at the same time. So, instead of making the second expression, do

if l.locked():
    l.release()

"", , , "", "" - , .

, /loolkits, .Net, , lock.acquire , , .

(Edit: "if l.locked: l.realse()". . Lock.locked cPython 2.6.x, 3.x, IronPython 2.6.1)

+6

, , , , . ?

+6

Since lock.acquire () returns true if it successfully receives the lock, you can save the lock state in a local variable and then encapsulate lock.acquire () and the subsequent code inside the try-finally block. Then, in the finally block, you can query the variable to find out if the lock was detected or not. If there is one, release it.

0
source

Source: https://habr.com/ru/post/1762690/


All Articles