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()

 

posted @ 2018-09-22 21:34  厚德载物_VIP  阅读(153)  评论(0编辑  收藏  举报