python 队列

2021-06-19 05:04

阅读:539

标签: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 :
            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


评论


亲,登录后才可以留言!