-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathlib03.03-Queue.py
More file actions
124 lines (87 loc) · 2.35 KB
/
lib03.03-Queue.py
File metadata and controls
124 lines (87 loc) · 2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
'''
Queue 模块
Queue 模块提供了一个线程安全的队列 (queue) 实现.
可以通过它在多个线程里安全访问同个对象.
'''
import threading
import queue
import time, random
WORKERS = 2
class Worker(threading.Thread):
"""docstring for Worker"""
def __init__(self, queue):
self.__queue = queue
threading.Thread.__init__(self)
def run(self):
while 1:
item = self.__queue.get()
if item is None:
break
time.sleep(random.randint(10, 100) / 1000.0)
print('task', item, 'finished')
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):
queue.put(None) # add end-of-queue markers
# 使用限制大小的 Queue 模块
# 如果队列满了, 那么控制主线程 (producer threads) 被阻塞, 等待项目被弹出 (pop off).
import threading
import queue
import time, random
WORKERS = 2
class Worker(threading.Thread):
"""docstring for Worker"""
def __init__(self, queue):
self.__queue = queue
threading.Thread.__init__(self)
def run(self):
while 1:
item = self.__queue.get()
if item is None:
break
time.sleep(random.randint(10, 100) / 1000.0)
print('task', item, 'finished')
# run with limited queue
queue = queue.Queue(3)
for i in range(WORKERS):
Worker(queue).start() # start a worker
for i in range(10):
print('push', i)
queue.put(i)
for i in range(WORKERS):
queue.put(None) # add end-of-queue markers
# 使用 Queue 模块实现优先级队列
# 可以通过继承 Queue 类来修改它的行为.
# 它接受一个元组作为参数, 元组的第一个成员表示优先级(数值越小优先级越高).
'''
import queue
import bisect
Empty = queue.Empty
class PriorityQueue(queue.Queue):
"""Thread-safe priority queue"""
def _put(self, item):
bisect.insort(self.queue, item)
queue = PriorityQueue(0)
# add items out of order
queue.put((20, 'second'))
queue.put((10, 'first'))
queue.put((30, 'third'))
# print queue contents
try:
while 1:
print(queue.get_nowait())
except Empty:
pass
'''
# 使用 Queue 模块实现一个堆栈
# 一个简单的堆栈 (stack) 实现 (末尾添加, 头部弹出, 而非头部添加, 头部弹出).
import queue
Empty = queue.Empty
class Stack(queue.Queue):
"""Thread-safe stack"""
def __init__(self, arg):
super(Stack, self).__init__()
self.arg = arg