condition.acquire vs lock.acquire

dieter dieter at handshake.de
Wed Mar 28 02:00:25 EDT 2018


jayshankar nair via Python-list <python-list at python.org> writes:
> Is condition.acquire(threading.Condition()) similar to lock.acquire(threading.Lock). Does both of get access to the lock. Can i use condition.wait,notify with lock.acquire or i have to use condition.wait, notify with condition.acquire.
> cond.acquire()  // can i replace with lock.acquire
>
>    while count[ipID]> 1:
>       cond.wait()
>    if ipID == 0:
>       time.sleep(10)
>
>
>    count[ipID] = count[ipID] + 1
>
>
>    cond.release() // can i replace with lock.release

The documentation tells you that a "condition" is always associated
with a "lock". You can either pass in a "lock" object when you
create a "condition" (in case, multiple "condition"s must share
the same lock) or such an object is created automatically.
The "condition"'s "acquire" and "release" methods call the respective
methods of this lock.

To determine whether you can call "lock.{acquire|release}"
(instead of "condition.{acquire|release}") look at
the implementation of the "condition" methods: if all
they do is delegating to the "lock" methods, it is safe; otherwise,
it is not safe.

Anyway, you should use "condition.{acquire|release}"
for clarity when working with "condition" (especially, calling its "wait",
"notify*" operations) rather than use the "lock" methods *UNLESS*
you have really good reasons to make use of the
"condition -> lock" association.




More information about the Python-list mailing list