解决多线程无返回值的问题

查看线程的源码内容(threading.py)python2.7的版本:

def run(self):
    """Method representing the thread's activity.

    You may override this method in a subclass. The standard run() method
    invokes the callable object passed to the object's constructor as the
    target argument, if any, with sequential and keyword arguments taken
    from the args and kwargs arguments, respectively.

    """
    try:
        if self.__target:
            self.__target(*self.__args, **self.__kwargs)
    finally:
        # Avoid a refcycle if the thread is running a function with
        # an argument that has a member that points to the thread.
        del self.__target, self.__args, self.__kwargs

可以看到,线程在start之后,只是运行了target的方法,并没有返回target方法的返回值,所以,我们需要重写线程的run函数。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import threading


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

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

def a(n):
    return n + 1

def main(ips):
    pp = [1,2,3,4,5]
    ths = list()
    for p in pp:
        t = ThreadResult(func=a, args=(p,))
        ths.append(t)
        t.start()

    t_results = list()
    for h in ths:
        h.join()
        t_results.append(h.result)
    return t_results

还有个方法是:在a函数的参数中,再传一个全局变量列表,用于存储本次调用a函数的执行结果。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值