转载

生产者消费者问题(6) – Python的Condition实现

按照网上找到的博文,先用condition实现。这种方式类似于Java的condition,区别在于Python的condition内含lock,而且是一对一的关系,而Java的lock里面含有condtion,可以一个lock对应多个condition。Python只要一个condition就可以同步互斥。

importsys, time fromthreadingimportThread fromthreadingimportCondition   buffer = 0; MAX_SIZE = 10; condition = Condition();   class Producer(Thread):   def__init__(self, name):     Thread.__init__(self);     self.name = name;     defrun(self):     global buffer     while True:       condition.acquire()       if buffer == MAX_SIZE:         print '%s: waiting' % self.name         condition.wait();       else:         print '%s: %s -> %s' % (self.name, buffer, buffer + 1)         buffer = buffer + 1         condition.notify()       condition.release()       time.sleep(1)     class Consumer(Thread):   def__init__(self, name):     Thread.__init__(self);     self.name = name;     defrun(self):     global buffer     while True:       condition.acquire()       if buffer == 0:         print '%s: waiting' % self.name         condition.wait();       else:         print '%s: %s -> %s' % (self.name, buffer, buffer - 1)         buffer = buffer - 1         condition.notify()       condition.release()       time.sleep(1)     if __name__ == '__main__':   if len(sys.argv) != 3:     exit('Usage: %s <producer> <consumer>' % sys.argv[0])   p = int(sys.argv[1])   c = int(sys.argv[2])     for m in range(p):     Producer('Producer %s' % m).start()     for n in range(c):     Consumer('Consumer %s' % n).start() 

那么,有没有更简单的方法呢。然后发现Python自带semaphore,所以接下来就用semaphore来实现。

原文  https://www.zhouchao.me/pc-python-condition/
正文到此结束
Loading...