【发布时间】:2014-04-16 17:38:17
【问题描述】:
我在 Python 中有这个示例,它演示了条件变量的使用。
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()
但是,它会在线程上引发运行时错误un-acquired lock。我有一个想法,我需要使用 acquire 和 release 函数,但我不确定它们的用法以及它们的作用。
【问题讨论】:
-
条件在哪里?当消费者拨打
wait时——它在等待什么?当产品调用notify时,它通知人们的事情在哪里?除非有条件(称为“谓词”),否则不能使用条件变量。
标签: python multithreading python-3.x python-2.x