记录一下python3中使用threading实现多线程,并获取每个线程调用的方法的返回值的方法:
import threading
import queue
import time
def test(i):
print('start---' + str(i))
time.sleep(i)
print('end---' + str(i))
return 'thread ' + str(i)
if __name__ == "__main__":
ths = [1, 2, 3, 4, 5]
th_list = []
que = queue.Queue()
for i in ths:
th = threading.Thread(target=lambda q, arg: q.put(test(arg)), args=(que, i))
th_list.append(th)
th.start()
for th in th_list:
th.join()
print(que.get())
# while not que.empty():
# print(que.get())
print('======== finish ==========')
结果:
start---1
start---2
start---3
start---4
start---5
end---1
thread 1
end---2
thread 2
end---3
thread 3
end---4
thread 4
end---5
thread 5
======== finish ==========