Python queue


#!/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