制片人/消费者:我应该为消费者写条件.release()吗?

时间:2018-05-20 13:57:49

标签: python multithreading

当我正在研究一个取自https://www.laurentluce.com/posts/python-threads-synchronization-locks-rlocks-semaphores-conditions-events-and-queues/的例子时,我看到如果我将self.condition.release()放入Consumer类的注释中,程序仍然会像以前一样。这部分是否必要,我应该写吗?

提前致谢。

代码是:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import time
import threading


class Producer(threading.Thread):
    def __init__(self, condition, variables):
        threading.Thread.__init__(self)
        self.condition = condition
        self.variables = variables

    def run(self):
        count = 1
        while count < 10:
            self.condition.acquire()
            print("condition was acquired by {}".format(self.name))
            self.variables.append(count)
            print("'{}' was appended to list by {}".format(count, self.name))
            self.condition.notify()
            print("condition was notified by {}".format(self.name))
            self.condition.release()
            print("condition was released by {}".format(self.name))
            count += 1
            time.sleep(0.5)


class Consumer(threading.Thread):
    def __init__(self, condition, variables):
        threading.Thread.__init__(self)
        self.condition = condition
        self.variables = variables

    def run(self):
        while True:
            self.condition.acquire()
            print("condition was acquired by {}".format(self.name))
            while True:
                if self.variables:
                    number = self.variables.pop()
                    print("'{}', was popped from list by {}".format(number, self.name))
                    break
                print("condition is waited by {}".format(self.name))
                self.condition.wait()
            # The part that i talked about is the below.
            # Should i put it out of the comment?
            # self.condition.release()
            # print("condition was released by {}".format(self.name))


__condition__ = threading.Condition()
__variables__ = []
t1 = Producer(condition=__condition__, variables=__variables__)
t2 = Consumer(condition=__condition__, variables=__variables__)
t1.start()
t2.start()

1 个答案:

答案 0 :(得分:1)

是的,那部分是必要的。否则当消费者线程突破while循环时,它将继续保持锁定,可能导致死锁。

您当前代码没有中断的原因是您只有一个消费者且消费者永远不会脱离循环。

相关问题