Skip to content

Commit 52002a6

Browse files
JINGJING
authored andcommitted
线程池使用
1 parent 8c6aa10 commit 52002a6

1 file changed

Lines changed: 35 additions & 0 deletions

File tree

thread_pool.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#!/usr/bin/env python
2+
#encoding:utf-8
3+
4+
import Queue, threading, time, random
5+
6+
NUM_WORKERS = 3
7+
thread_pool = []
8+
9+
class MyThread(threading.Thread):
10+
def __init__(self, queue, thread_no, processer):
11+
self.queue = queue
12+
self.thread_no = thread_no
13+
self.processer = processer
14+
threading.Thread.__init__(self, name = thread_no)
15+
16+
def run(self):
17+
while self.queue.qsize() > 0:
18+
self.processer(self.queue.get(), self.thread_no)
19+
20+
def doTask(task, thread_no):
21+
time.sleep(random.random() * 3)
22+
print "doing", task, "thread_no", thread_no
23+
24+
if __name__ == "__main__":
25+
print "begin..."
26+
q = Queue.Queue(0)
27+
28+
map(lambda x : q.put(x), range(NUM_WORKERS * 2))
29+
print "job qsize:", q.qsize()
30+
map(lambda x : thread_pool.append(MyThread(q, x, doTask)), range(NUM_WORKERS))
31+
map(lambda x : x.setDaemon(True), thread_pool)
32+
map(lambda x : x.start(), thread_pool)
33+
map(lambda x : x.join(), thread_pool)
34+
35+
print "done"

0 commit comments

Comments
 (0)