python 队列
Posted 山外云
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 队列相关的知识,希望对你有一定的参考价值。
队列--存放对象的容器
#coding:utf-8 import queue import time q = queue.Queue() for i in range(10): q.put(i) while not q.empty(): print(\'从队列中取出的元素: %s\' % q.get()) time.sleep(0.5)
生产者消费者模型
#coding:utf-8 import time import threading import queue import os from threading import Thread q = queue.Queue() class Consumer(Thread): def __init__(self, q): Thread.__init__(self) self.q = q def run(self): while True: msg = self.q.get() print(msg) if isinstance(msg, str) and msg == \'finish\': break os.rename(msg , msg+\'.bak\') print(\'byebye\') class Producer(Thread): def __init__(self, q): Thread.__init__(self) self.q = q def run(self): start_time = time.time() i = 0 while time.time() - start_time < 10: fullpath = r"C:\\Users\\Martin\\Desktop\\xxx\\test\\%s" % str(time.time()) i += 1 f = open(fullpath, \'w\') f.close() self.q.put(fullpath) time.sleep(1) self.q.put(\'finish\') worker = Consumer(q) worker.start() producer = Producer(q) producer.start()
以上是关于python 队列的主要内容,如果未能解决你的问题,请参考以下文章