笔记,主要是理解多线程的线程池,关注标红的部分
不要在意process函数是干什么的,只理解为一个函数即可,最后一句是释放该线程
本例就是,最多20个线程,不断地利用和释放
import threading
# 程序执行入口
def execute(self):
result = self.fetch_hosts()
if not result:
return None
#
def process(self, hostname, thread_obj):
try:
server_response = PluginApi.get_server_info(hostname, self.remote_user, self.remote_port)
if not server_response.status:
raise Exception(server_response.message)
params = urllib.urlencode({"data": json.dumps(server_response.data)})
# 将获取的主机信息发送到API处理,但API返回数据未做任何处理
self.url_request(self.push_resource, ‘POST‘, params)
except Exception, e:
log.write_error_log(‘[%s][process],%s‘ % (hostname, str(e)))
finally:如果不这样做,那么并发10000个甚至更多,
就会来多少请求,创建多少个线程,服务器可能瞬间崩溃。
比如:
def run(n): print ‘run‘ for i in range(1000): t = threading.Thread(target=run, args=(i,)) t.start()
这个例子就会瞬间起1000个线程
原文:http://yunweipy.blog.51cto.com/10683003/1694655