查看线程的源码内容(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函数的执行结果。