Created
August 8, 2013 13:36
-
-
Save liuzhe0223/6184627 to your computer and use it in GitHub Desktop.
python的一个线程池, 我自认为是java风格的
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
#coding:utf-8 | |
import threading | |
from Queue import Queue | |
class ThreadPool(threading.Thread): | |
def __init__(self, max_nu): | |
threading.Thread.__init__(self) | |
self.max_nu=max_nu | |
self.task_pool=Queue(max_nu) | |
self.runing_pool=[] | |
self.setDaemon(True) | |
self.start() | |
def put(self, thread): | |
self.task_pool.put(thread) | |
def run(self): | |
for i in xrange(self.max_nu): | |
self.runing_pool.append(self.task_pool.get()) | |
try: | |
self.runing_pool[i].start() | |
except: | |
print "is not a thread object instance" | |
while True: | |
for i in xrange(self.max_nu): | |
if self.runing_pool[i].isAlive(): | |
continue | |
else: | |
self.runing_pool[i]=self.task_pool.get() | |
self.runing_pool[i].start() | |
time.sleep(0.1) | |
def wait_all(self): | |
class TaskThread(threading.Thread): | |
def __init__(self, nu): | |
threading.Thread.__init__(self) | |
self.nu=nu | |
def run(self): | |
for i in xrange(10): | |
print self.nu | |
time.sleep(1) | |
if __name__ == "__main__": | |
thread_pool=ThreadPool(20) | |
for i in xrange(100): | |
t=TaskThread(i) | |
thread_pool.put(t) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment