我想有两个任务。一个是生产者,另一个是消费者。为了生成新的数据,生产者必须等待消费者消费数据。执行流程必须是:fpga、bbb、fpga、bbb、fpga、bbb、fpga、bbb、fpga、bbb。。。。。 当我有一个大的睡眠时间为生产者每件事都很好,但当睡眠时间很短,我有一个僵局。有人知道为什么吗?我的代码:
class fpga (threading.Thread):
def __init__(self,condition,data):
threading.Thread.__init__(self)
self.name='fpga'
self.condition=condition
self.data=data
self.sleepTime=1.0/(300.0*18.0)
self.count=0
def run(self):
while True:
newData='YxxY'
self.condition.acquire()
self.condition.notify()
self.condition.wait()
self.condition.release()
time.sleep(self.sleepTime) #sleep some time
print 'fpga'
class bbb (threading.Thread):
def __init__(self,condition,data):
threading.Thread.__init__(self)
self.name='bbb'
self.condition=condition
self.data=data
def run (self):
while True:
self.condition.acquire()
self.condition.wait()
self.condition.notify()
self.condition.release()
print 'bbb'
if __name__=='__main__':
dataFpga=[]
dataFromFpgaCondition=threading.Condition()
threadfpga=fpga(dataFromFpgaCondition,dataFpga)
threadBbb=bbb(dataFromFpgaCondition,dataFpga)
threadBbb.start()
threadfpga.start()
threadBbb.join()
threadfpga.join()
你的代码里有一场比赛。在
您的制作人
fpga
需要执行以下操作:acquire
condition
锁notify
另一个线程release
condition
锁消费者
bbb
需要执行以下操作:acquire
condition
锁wait
得到数据可用的通知(重要:这将释放锁)notify
完成处理的生产商release
condition
锁您的消费者正在执行上述步骤:
但是,您的制作人没有遵循以下步骤:
^{pr2}$您在调用
notify
后立即有一个不必要的wait
调用。这将引入竞争条件。你可以这样结束:您可以通过添加
sleep
调用来避免这种情况,因为一旦我们到达竞速点,生产者就会暂停sleep
,这将让消费者获胜。如果没有睡眠,或者睡眠时间很短,制作人就可以获胜。在修复方法只是删除在producer中对
self.condition.wait()
的调用。在可能两个线程
wait
为另一个线程,例如下面的调度很快就会导致死锁。在
您的方法无法工作,因为
notify
没有“记住”,如果在执行notify
时没有等待线程,则通知将丢失。在相关问题 更多 >
编程相关推荐