Odoo中文网|Odoo实施培训

 找回密码
 立即注册
搜索
热搜: Odoo OpenERP 实施
查看: 6194|回复: 0
打印 上一主题 下一主题

python多线程(threading)

[复制链接]

17

主题

19

帖子

75

积分

注册会员

Rank: 2

积分
75
跳转到指定楼层
楼主
发表于 2015-9-16 06:43:19 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式

# -*- 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)()
'''

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|手机版|小黑屋|技术支持|开发手册|Odoo中文网-远鼎旗下odoo培训网站 ( 苏ICP备15039516号 )

GMT+8, 2024-5-8 14:25 , Processed in 0.010433 second(s), 9 queries , Xcache On.

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表