#!/usr/bin/env python # -*- coding:utf-8 -*- # author: Changhua Gong import queue from queue import Queue ‘‘‘ class queue.Queue(maxsize=0) #先入先出 class queue.LifoQueue(maxsize=0) #last in fisrt out class queue.PriorityQueue(maxsize=0) #存储数据时可设置优先级的队列 方法: Queue.qsize() Queue.empty() #return True if empty Queue.full() # return True if full Queue.put(item, block=True, timeout=None) Queue.put_nowait(item) Equivalent to put(item, False). Queue.get(block=True, timeout=None) Queue.get_nowait() Equivalent to get(False). Queue.task_done() Two methods are offered to support tracking whether enqueued tasks have been fully processed by daemon consumer threads. 有两个方法用来跟踪消费线程中处理的对列任务是否被完全处理 Queue.task_done() Indicate that a formerly enqueued task is complete. Used by queue consumer threads. For each get() used to fetch a task, a subsequent call to task_done() tells the queue that the processing on the task is complete. Queue.task_done()表明当前对列任务完成,对于每个get方法获取一个任务,后来对task_done方法的调用 告诉对列这个任务处理完毕。 If a join() is currently blocking, it will resume when all items have been processed (meaning that a task_done() call was received for every item that had been put() into the queue). 如果join方法正在阻塞,所有的items会被继续处理完成,意味着对列中的每个item都会收到task_done()的通知 Raises a ValueError if called more times than there were items placed in the queue. Blocks until all items in the Queue have been gotten and processed. Queue.join() block直到queue被消费完毕 The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer thread calls task_done() to indicate the item was retrieved and all work on it is complete. When the count of unfinished tasks drops to zero, join() unblocks. 当未完成的任务数量下降至0时,join不再阻塞 ‘‘‘ import threading import queue def producer(): for i in range(10): q.put("骨头 %s" % i) print("开始等待所有的骨头被取走...") q.join() print("所有的骨头被取完了...") def consumer(n): while q.qsize() > 0: print("%s 取到" % n, q.get()) q.task_done() # 告知这个任务执行完了 q = queue.Queue() p = threading.Thread(target=producer, ) p.start() consumer("李闯") print("****************************************************************") import time,random import queue,threading q = queue.Queue() def Producer(name): count = 0 while count <20: time.sleep(random.randrange(3)) q.put(count) print(‘Producer %s has produced %s baozi..‘ %(name, count)) count +=1 def Consumer(name): count = 0 while count <20: time.sleep(random.randrange(4)) if not q.empty(): data = q.get() print(data) print(‘\033[32;1mConsumer %s has eat %s baozi...\033[0m‘ %(name, data)) else: print("-----no baozi anymore----") count +=1 p1 = threading.Thread(target=Producer, args=(‘A‘,)) c1 = threading.Thread(target=Consumer, args=(‘B‘,)) p1.start() c1.start()
From: alex example
本文出自 “90SirDB” 博客,请务必保留此出处http://90sirdb.blog.51cto.com/8713279/1926910
原文地址:http://90sirdb.blog.51cto.com/8713279/1926910