threading.Condition通知错过了

时间:2016-02-19 07:17:04

标签: python

我创建了用于理解python中threading.Condition的示例程序。在哪个生产者类中将生成一些数字并发送给消费者类。消费者类将简单地取得收到的数字的平方。

代码:

class ConditionProducer(threading.Thread):
    """ Create numbers till limt """

    def __init__(self, condition, limit, buf):
        super(ConditionProducer, self).__init__()
        self.limit = limit
        self.condition = condition

    def run(self):
        for i in range(self.limit):
            with self.condition:
                print "Creating Number %d" % i
                buf[0] = i
                self.condition.notify()
                time.sleep(.5)

class ConditionConsumer(threading.Thread):
    """ Create Square of number generated by producer """

    def __init__(self, condition, buf):
        super(ConditionConsumer, self).__init__()
        self.condition = condition

    def run(self):
        with self.condition:            
            while True:
                sqr = buf[0] * buf[0]
                print "The Square of number is %d" % sqr
                self.condition.wait()
                time.sleep(.1)


if __name__ == '__main__':
    buf = [-1]
    condition = threading.Condition()
    t1 = ConditionProducer(condition, 10, buf)
    t2 = ConditionConsumer(condition, buf)
    t2.start()
    t1.start()

我得到了以下输出:

ubuntu:~$ python thread.py 
The Square of number is 1

Creating Number 0
The Square of number is 0
Creating Number 1
The Square of number is 1
Creating Number 2
Creating Number 3
Creating Number 4
Creating Number 5
Creating Number 6
Creating Number 7
Creating Number 8
Creating Number 9
The Square of number is 81

在上面的代码中,消费者的睡眠时间少于生产者的睡眠时间。所以消费者没有机会错过制片人的通知。那么,为什么输出中缺少一些数字的平方?

1 个答案:

答案 0 :(得分:0)

我无法确定问题所在的部分,但是当您更改生产者和消费者共享的公共列表时,可以使用lock。 这个问题主要是由于竞争条件造成的。