首页 > 代码库 > python多线程之Condition(条件变量)
python多线程之Condition(条件变量)
#!/usr/bin/env python# -*- coding: utf-8 -*-from threading import Thread, Conditionimport timeitems = []condition = Condition()class Consumer(Thread): def __init__(self): Thread.__init__(self) def consume(self): global condition global items condition.acquire() if len(items) == 0: condition.wait() print ("Consumer notify: no item to consume") items.pop() print("Consumer notify: consumed 1 item") print("Consumer nofity: items to consume are " + str(len(items))) condition.notify() condition.release() def run(self): for i in range(0, 20): time.sleep(4) self.consume()class Producer(Thread): def __init__(self): Thread.__init__(self) def produce(self): global condition global items condition.acquire() if len(items) == 10: condition.wait() print ("Producer notify: item producted are" + str(len(items))) print("Producer nofity: stop the production!!") items.append(1) print("Producer nofity: total items producted " + str(len(items))) condition.notify() condition.release() def run(self): for i in range(0, 20): time.sleep(1) self.produce()if __name__ == "__main__": producer = Producer() consumer = Consumer() producer.start() consumer.start() producer.join() consumer.join()
python多线程之Condition(条件变量)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。