## python队列模块Queue

2015年7月15日 发表评论 阅读评论

### 一、初识Queue模块

```先进先出  q = Queue.Queue(maxsize)

Queue.qsize() 返回队列的大小
Queue.empty() 如果队列为空，返回True,反之False
Queue.full() 如果队列满了，返回True,反之False
Queue.full 与 maxsize 大小对应
Queue.put(item) 写入队列，timeout等待时间   非阻塞
Queue.get([block[, timeout]]) 获取队列，timeout等待时间
Queue.get_nowait() 相当Queue.get(False)
Queue.put_nowait(item) 相当Queue.put(item, False)
Queue.join()： 实际上意味着等到队列为空，再执行别的操作 ```

### 二、队列示列

#### 1、FIFO(先进先出)

```import Queue
q = Queue.Queue()
for i in range(5):
q.put(i)
while not q.empty():
print q.get()```

```[root@361way queue]# python fifo.py
0
1
2
3
4```

#### 2、LIFO（后进先出）

```import Queue
q = Queue.LifoQueue()
for i in range(5):
q.put(i)
while not q.empty():
print q.get()```

```import Queue
q = Queue.LifoQueue()
for i in range(5):
q.put(i)
while not q.empty():
print q.get()```

#### 3、带优先级的队列

```import Queue
class Job(object):
def __init__(self, priority, description):
self.priority = priority
self.description = description
print 'New job:', description
return
def __cmp__(self, other):
return cmp(self.priority, other.priority)
q = Queue.PriorityQueue()
q.put( Job(3, 'Mid-level job') )
q.put( Job(10, 'Low-level job') )
q.put( Job(1, 'Important job') )
while not q.empty():
next_job = q.get()
print 'Processing job:', next_job.description```

```[root@361way queue]# python Queue_priority.py
New job: Mid-level job
New job: Low-level job
New job: Important job
Processing job: Important job
Processing job: Mid-level job
Processing job: Low-level job```

### 三、队列与线程

```from Queue import *
import sys
'''this function will process the items in the queue, in serial'''
def processor():
while True:
if queue.empty() == True:
print "the Queue is empty!"
sys.exit(1)
try:
job = queue.get()
print "I'm operating on job item: %s"%(job)
except:
print "Failed to operate on job"
'''set variables'''
queue = Queue()
'''a list of job items. you would want this to be more advanced,
like reading from a file or database'''
jobs = [ "job1", "job2", "job3" ]
'''iterate over jobs and put each into the queue in sequence'''
#for job in jobs:
for job in range(100):
print "inserting job into the queue: %s"%(job)
queue.put(job)
'''start some threads, each one will process one job from the queue'''
#for i in range(100):
th.setDaemon(True)
th.start()
'''wait until all jobs are processed before quitting'''
queue.join()```

```[root@361way tmp]# python queue-example-1.py
[root@361way tmp]# more queue-example-1.py
# File: queue-example-1.py
import Queue
import time, random
WORKERS = 2
def __init__(self, queue):
self.__queue = queue
def run(self):
while 1:
item = self.__queue.get()
if item is None:
break # reached end of queue
# pretend we're doing something that takes 10-100 ms
time.sleep(random.randint(10, 100) / 1000.0)
#
# try it
queue = Queue.Queue(0)
for i in range(WORKERS):
Worker(queue).start() # start a worker
for i in range(10):
queue.put(i)
for i in range(WORKERS):
```

You can donate through PayPal.
My paypal id: itybku@139.com
Paypal page: https://www.paypal.me/361way

1. 本文目前尚无任何评论.