获取python多线程运行结果,我们要实现多线程类,在类中添加获取结果的方法,任意函数名都可以
看如下两个例子:
例1:
# coding:utf-8
import time
from threading import Thread
def foo(number):
time.sleep(20)
return number
class MyThread(Thread):
def __init__(self, number):
Thread.__init__(self)
self.number = number
def run(self):
self.result = foo(self.number)
def get_result(self):
return self.result
thd1 = MyThread(3)
thd2 = MyThread(5)
thd1.start()
thd2.start()
thd1.join()
thd2.join()
print thd1.get_result()
print thd2.get_result()
例2:
#coding=utf-8
import threading
import time
class MyThread(threading.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 # 如果子线程不使用join方法,此处可能会报没有self.result的错误
except Exception:
return None
def foo(a,b,c):
# time.sleep(1)
# print a*2,b*2,c*2,
if a == 0:
time.sleep(10)
return a*2,b*2,c*2
st = time.time()
li = []
for i in xrange(4):
t = MyThread(foo,args=(i,i+1,i+2))
li.append(t)
t.start()
for t in li:
t.join() # 一定要join,不然主线程比子线程跑的快,会拿不到结果
print t.get_result()
et = time.time()
print et - st
测试发现,例2中返回的结果是有序的