码迷,mamicode.com
首页 > 编程语言 > 详细

python 队列

时间:2018-09-22 21:57:25      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:com   对象   ons   pre   str   cer   div   art   produce   

队列--存放对象的容器

#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 队列

标签:com   对象   ons   pre   str   cer   div   art   produce   

原文地址:https://www.cnblogs.com/hellojackyleon/p/9691306.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!