Python多线程

Odoo多线程应用参考


from threading import Thread

class SyncTask(object):
    """
    同步任务
    """
    
    def run(self):      
        task_name_list = [ ... ]
        
        task_func_list = [ ... ]

        
            times = []
            results = []
            statuses = {}
            for i in range(len(task_name_list)):
                thread_task = SyncTaskThread(task_func_list[i], task_name_list[i])
                threads.append(thread_task)
            for i in range(len(task_name_list)):
                threads[i].start()
            for i in range(len(task_name_list)):
                threads[i].join()

            for t in threads:
                if t.is_alive():
                    pass
                else:
                    time, status, result = t.result
                    statuses.update(status)
                    times.append(time)
                    results.append(
                        _("%s, time spent: " "%s seconds") % (result, round(time, 3))
                    )

            results = "\n".join(results)

            return sum(times), statuses, results

class SyncTaskThread(Thread):
    def __init__(selffuncname=""):
        Thread.__init__(self)
        self.name = name
        self.func = func
        self.result = self.func()

    def get_result(self):
        try:
            return self.result
        except Exception:
            return None