<br /># -*- coding: utf-8 -*- <br />#author:ghoti<br />'''自定义多线程运行函数,可定义同时运行个数'''<br />import threading,time<br />from time import sleep,ctime<br />class My_Thead:<br /> '''<br /> 多线程运行函数,将all_list切片处理,num为进程数,all_list小于num,单线程运行,<br /> sleep_time为单个进程(一个all_list切片)运行后停留时间(方便调试),<br /> myfunc为处理每个切片的函数,对all_list切片,在处理<br /> '''<br /> def __init__ (self, all_list, num, sleep_time=0, myfunc=None):<br /> self.all_list = all_list<br /> self.len_list = len(all_list)<br /> self.num = num #进程数,实际进程为可能为num+1<br /> if len(all_list)<num:<br /> self.num = 1<br /> self.m = self.len_list/self.num<br /> if not self.m:<br /> self.m = 1<br /> self.loops=range(0 , self.len_list, self.m)<br /> self.sleep_time = sleep_time<br /> self.myfunc = myfunc<br /> def loop (self,nloop,n,m):<br /> self.myfunc(n,m)<br /> sleep(self.sleep_time)<br /> def __call__ (self):<br /> if not self.all_list:<br /> return False<br /> threads=[]<br /> nloops=range(len(self.loops))<br /> for i in nloops:<br /> t=threading.Thread(target=self.loop,args=(i, self.loops[i], self.m))<br /> threads.append(t)<br /> for i in nloops:<br /> threads[i].start()<br /> for i in nloops:<br /> threads[i].join()<br /><br />'''<br />##how to use<br />#from my_thread import My_Thead<br />all_list = range(103)<br />def myfunc(n,m):<br /> part_list = all_list[n:n+m]<br /> for i in part_list:<br /> print i,<br />My_Thead(range(103),5,myfunc=myfunc)()<br />'''<br /><br />''' <br />## use in oe<br /> def myfunc(n,m):<br /> part_list = rsps[n:n+m]<br /> for rsp in part_list:<br /> self.action_do_product(cr, uid, ids, rsp, context=None):<br /> <br /> from openerp.addons.basefunc.my_thread import My_Thead<br /> My_Thead(rsps,10,myfunc=myfunc)()<br />'''<br />