|
| 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