python 多线程下的优化
程序员文章站
2022-05-02 18:07:36
...
第一个版本:
场景:
我有一个函数,传入一个参数,执行需要耗时5s,现在我有一个列表存着1000个参数,需要遍历 让这个函数去执行。
实现方式:
多线程(必须保证线程安全)
# !/usr/bin/env python
# -*- coding:utf-8 -*-
import Queue
import threading
import time
class WorkManager(object):
def __init__(self, work_list=None,thread_num=2):
self.work_queue = Queue.Queue()
self.threads = []
self.__init_work_queue(work_list)
self.__init_thread_pool(thread_num)
"""
初始化线程
"""
def __init_thread_pool(self,thread_num):
for i in range(thread_num):
self.threads.append(Work(self.work_queue))
"""
初始化工作队列
"""
def __init_work_queue(self, jobs_list):
for i in (jobs_list):
self.add_job(do_job, i)
"""
添加一项工作入队
"""
def add_job(self, func, *args):
self.work_queue.put((func,list(args)))#任务入队,Queue内部实现了同步机制
"""
等待所有线程运行完毕
"""
def wait_allcomplete(self):
for item in self.threads:
if item.isAlive():item.join()
class Work(threading.Thread):
def __init__(self, work_queue):
threading.Thread.__init__(self)
self.work_queue = work_queue
self.start()
def run(self):
#死循环,从而让创建的线程在一定条件下关闭退出
while True:
try:
do, args = self.work_queue.get(block=False)#任务异步出队,Queue内部实现了同步机制
do(args)
self.work_queue.task_done()#通知系统任务完成
except:
break
#具体要做的任务
def do_job(args):
time.sleep(2)#模拟处理时间
print args[0]
#print threading.current_thread(), list(args)
if __name__ == '__main__':
start = time.time()
test_list = ["zhangsan","lisi","wangwu","zhaoliu","cc","ie"]
work_manager = WorkManager(work_list=test_list,thread_num=2)#或者work_manager = WorkManager(10000, 20)
work_manager.wait_allcomplete()
end = time.time()
print "cost all time: %s" % (end-start)
输出结果:
zhangsan
lisi
wangwuzhaoliu
cc
ie
cost all time: 6.00967502594
缺陷:如果这个函数有返回值。这个代码得改改。2个方案吧
方案一:使用全局Queue队列存储。然后遍历取值
# !/usr/bin/env python
# -*- coding:utf-8 -*-
import Queue
import threading
import time
res = Queue.Queue()
class WorkManager(object):
def __init__(self, work_list=None,thread_num=2):
self.work_queue = Queue.Queue()
self.threads = []
self.__init_work_queue(work_list)
self.__init_thread_pool(thread_num)
"""
初始化线程
"""
def __init_thread_pool(self,thread_num):
for i in range(thread_num):
self.threads.append(Work(self.work_queue))
"""
初始化工作队列
"""
def __init_work_queue(self, jobs_list):
for i in (jobs_list):
self.add_job(do_job, i)
"""
添加一项工作入队
"""
def add_job(self, func, *args):
self.work_queue.put((func,list(args)))#任务入队,Queue内部实现了同步机制
"""
等待所有线程运行完毕
"""
def wait_allcomplete(self):
for item in self.threads:
if item.isAlive():item.join()
class Work(threading.Thread):
def __init__(self, work_queue):
threading.Thread.__init__(self)
self.work_queue = work_queue
self.start()
def run(self):
#死循环,从而让创建的线程在一定条件下关闭退出
while True:
try:
do, args = self.work_queue.get(block=False)#任务异步出队,Queue内部实现了同步机制
do(args)
self.work_queue.task_done()#通知系统任务完成
except:
break
#具体要做的任务
def do_job(args):
time.sleep(2)#模拟处理时间
#print args[0]
#print threading.current_thread(), list(args)
res.put({"name":args})
if __name__ == '__main__':
start = time.time()
test_list = ["zhangsan","lisi","wangwu","zhaoliu","cc","ie"]
work_manager = WorkManager(work_list=test_list,thread_num=2)#或者work_manager = WorkManager(10000, 20)
work_manager.wait_allcomplete()
for i in range(len(test_list)):
print res.get()
end = time.time()
print "cost all time: %s" % (end-start)
输出:
{'name': ['zhangsan']}
{'name': ['lisi']}
{'name': ['wangwu']}
{'name': ['zhaoliu']}
{'name': ['cc']}
{'name': ['ie']}
cost all time: 6.01245284081
算是一个方案吧,函数不定义return 而是把结果存储到公共的队列里
方案二:重新定义Thread 类方法。取返回值