5

I have this example in Python which demonstrates the use of condition variables.

import logging
import threading
import time

logging.basicConfig(level=logging.DEBUG, format='%(asctime)s (%(threadName)-2s) %(message)s',)

def consumer(cond):

    # wait for the condition and use the resource

    logging.debug('Starting consumer thread')

    t = threading.currentThread()

    cond.wait()

    logging.debug('Resource is available to consumer')

def producer(cond):

    # set up the resource to be used by the consumer

    logging.debug('Starting producer thread')

    logging.debug('Making resource available')

    cond.notifyAll()


condition = threading.Condition()

# pass each thread a 'condition'
c1 = threading.Thread(name='c1', target=consumer, args=(condition,))
c2 = threading.Thread(name='c2', target=consumer, args=(condition,))
p = threading.Thread(name='p', target=producer, args=(condition,))


# start two threads and put them into 'wait' state
c1.start()
c2.start()

# after two seconds or after some operation notify them to free or step over the wait() function
time.sleep(2)
p.start()

However, it raises a runtime error un-acquired lock on threads. I have an idea that I need to use acquire and release functions but I'm not sure about their usage and what exactly they do.

1
  • Where is the condition? When the consumer calls wait -- where is the thing it's waiting for? When the produces calls notify, where is the thing it's notifying people about? You can't use a condition variable unless you have a condition (called a "predicate"). Apr 16, 2014 at 18:17

1 Answer 1

16

Conditions are a wrapper around an underlying Lock that provide wait/notify functionality. You need to acquire a lock before you can release it - which wait does under the hood. Notably once it gets re-awoken, it reacquires the lock. Thus mutual exclusion is ensured between acquiring and releasing, with wait "yielding" control of the lock, if that makes sense.

Instead of doing the acquiring/releasing manually, just use the Condition as a context manager:

def consumer(cond):
    with cond:
        cond.wait()

    logging.debug('Resource is available to consumer')

If for whatever reason you're stuck on a version of python without context managers, this is equivalent to:

def consumer(cond):
    try:
        cond.acquire()
        cond.wait()
    finally:
        cond.release()

    logging.debug('Resource is available to consumer')

Often you want to make sure that only one consumer gets awoken, so the following idiom is frequently used:

with cond:
    while some_queue.isEmpty():
        cond.wait()
    #get one from queue

Thus you could notify any number of consumers and the extra ones just go immediately back to sleep once the Queue is empty.

5
  • In Python 2.5 as there is not with statement, would I put acquire and release around the wait function?
    – cpx
    Apr 16, 2014 at 18:16
  • You need to wrap things with try/finally to get the same semantics as a context manager, see edit.
    – roippi
    Apr 16, 2014 at 18:18
  • What does this lock do and why do you need it?
    – cpx
    Apr 16, 2014 at 19:23
  • A Lock ensures that only one thread can enter a given code block at a given time - aka mutual exclusion. You "need" it only so far as that's how Condition works, I can't answer more than that. Maybe what you're trying to do doesn't actually need a condition, but I can't really tell you that.
    – roippi
    Apr 16, 2014 at 19:44
  • On that website they don't put the cond.acquire() into the try statement, and I would say they are right not do so : it makes it more understandable. When you don't know about it you are like "why would you have to put the acquire into the try statement?". And that is not a relevant question as you don't have to put it in there. By the way, the linked website helped me a lot in understanding threading in Python, hope it could help anyone else
    – DRz
    Aug 5, 2016 at 22:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.