Python 获取多线程返回值的两种方式

1. 通过复写Thread类,自定义一个get_result()方法

from threading import Thread


# _sum = 0


def cal_sum(begin, end):
    # global _sum
    _sum = 0
    for i in range(begin, end + 1):
        _sum += i
    return  _sum

"""重新定义带返回值的线程类"""


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

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

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


if __name__ == '__main__':
    t1 = MyThread(cal_sum, args=(1, 5))
    t2 = MyThread(cal_sum, args=(6, 10))
    t1.start()
    t2.start()
    t1.join()
    t2.join()
    res1 = t1.get_result()
    res2 = t2.get_result()

    print(res1 + res2)

2. 使用全局变量

from threading import Thread

_sum = 0


def cal_sum(begin, end):
    # 声明使用全局变量
    global _sum
    for i in range(begin, end + 1):
        _sum += i


if __name__ == '__main__':
    t1 = Thread(target=cal_sum, args=(1, 5))
    t2 = Thread(target=cal_sum, args=(6, 10))
    t1.start()
    t2.start()

    print(_sum)

第二种方法简单一些,我个人还是比较喜欢用第一种方式。

你可能感兴趣的:(Python)