Fil des variables de condition: onu-verrou acquis

J'ai cet exemple en Python qui illustre l'utilisation de variables de condition.

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()

Cependant, il génère une erreur d'exécution un-acquired lock sur les threads. J'ai une idée que j'ai besoin d'utiliser acquire et release fonctions mais je ne suis pas sûr au sujet de leur utilisation et de ce que exactement ce qu'ils font.

Où est la condition? Lorsque le consommateur appelle wait -- où est la chose qu'il attend? Lorsque le produit des appels notify, où est la chose, c'est informer les personnes au sujet? Vous ne pouvez pas utiliser une variable de condition, à moins que vous avez une condition (appelé un "prédicat").

OriginalL'auteur cpx | 2014-04-16