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