python 多任务中获取返回值

带返回值函数的多任务

1. 多线程的返回值问题

python 多线程基于 较为底层的thread模块. 使用中, python 的 threading
模块是对thread做了⼀些包装的,可以更加⽅便的被使⽤ . 但是直接通过threading类调用目标函数, 无法获得目标函数的返回值, 因此需要通过重写 threading的 Thread类来获取返回值. 资料可见的几种方法如下:

# –*– coding: utf-8 –*–
# @Time      : 2019/3/17 15:48
# @Author    : Damon_duanlei
# @FileName  : mythread_01.py
# @BlogsAddr : https://blog.csdn.net/Damon_duanlei

import threading
import time


class MyThread(threading.Thread):
    def __init__(self, func, args=()):
        super(MyThread, self).__init__()
        self.func = func
        self.args = args
        self._result = None

    def run(self):
        self._result = self.func(*self.args)

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

也可通过重写 Thread 的 join 方法来获取:

# –*– coding: utf-8 –*–
# @Time      : 2019/3/17 15:48
# @Author    : Damon_duanlei
# @FileName  : mythread_01.py
# @BlogsAddr : https://blog.csdn.net/Damon_duanlei

import threading
import time


class MyThread(threading.Thread):
    def __init__(self, func, args=()):
        super(MyThread, self).__init__()
        self.func = func
        self.args = args
        self._result = None

    def run(self):
        self._result = self.func(*self.args)

    def join(self):
        threading.Thread.join(self)
        return self._result

另,还见过在初始化自定义类时就调用目标函数获取返回值, 几种方法各有利弊, 可根据实际应用场景进行选择

# –*– coding: utf-8 –*–
# @Time      : 2019/3/17 15:48
# @Author    : Damon_duanlei
# @FileName  : mythread_01.py
# @BlogsAddr : https://blog.csdn.net/Damon_duanlei

import threading
import time


class MyThread(threading.Thread):
    def __init__(self, func, args, name=''):
        threading.Thread.__init__(self)
        self.name = name
        self.func = func
        self.args = args
        self.result = self.func(*self.args)

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

未完待续…

你可能感兴趣的:(自学总结,python,多线程)