代码之家  ›  专栏  ›  技术社区  ›  dildeolupbiten

生产者/消费者:我应该为消费者编写condition.release()吗?

  •  1
  • dildeolupbiten  · 技术社区  · 7 年前

    当我学习一个例子时, https://www.laurentluce.com/posts/python-threads-synchronization-locks-rlocks-semaphores-conditions-events-and-queues/ ,我看到如果我把 self.condition.release() 在消费类的评论中,程序仍然和以前一样。这部分有必要吗,我应该写吗?

    事先谢谢。

    代码为:

    #!/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 回复  |  直到 7 年前
        1
  •  1
  •   NPE    7 年前

    是的,那部分是必要的。否则,当用户线程从 while 循环它将继续持有锁,可能导致死锁。

    您当前的代码没有中断的原因是您只有一个使用者,而该使用者从未中断过循环。