python 多线程,并且返回函数方法的值
#!/usr/bin/env python
#-*- coding: utf-8 -*-
from time import ctime, sleep
import threading
import time
loops = ['江西', '吉安']
class MyThread(threading.Thread):
"""
重构threading方法,单独写一个获取返回值的方法,get_result
"""
def __init__(self, func, args, name=''):
threading.Thread.__init__(self)
self.name = name
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
def loop(n):
print("task", n)
time.sleep(1)
print('2s')
time.sleep(1)
print('1s')
time.sleep(1)
print('0s')
time.sleep(1)
return n
def main():
print('start at', ctime())
threads = []
nloops = range(len(loops))
for i in nloops:
t = MyThread(loop, (loops[i],), loop.__name__)
threads.append(t)
for i in nloops: # start threads 此处并不会执行线程,而是将任务分发到每个线程,同步线程。等同步完成后再开始执行start方法
threads[i].start()
for i in nloops: # jion()方法等待线程完成
threads[i].join()
print("loop.__name__",loop.__name__)
print(threads[1].get_result())
print('DONE AT:', ctime())
if __name__ == '__main__':
main()
结果
start at Wed Feb 3 18:23:29 2021
task 江西
task 吉安
2s2s
1s
1s
0s
0s
loop.__name__ loop
吉安
DONE AT: Wed Feb 3 18:23:33 2021