之前一直直接使用Thread去做python多线程的测试,start开始线程,然后join去等待结束等等。
import threading
import time
def add(x,y):
print("the res is %d" % (x+y))
time.sleep(x)
print("the thread is over")
x1=1
x2=2
y1=1
y2=2
T_list=[]
T1 = threading.Thread(target=add,args=(x1,y1))
T_list.append(T1)
T2 = threading.Thread(target=add,args=(x2,y2))
T_list.append(T2)
for i in T_list:
i.start()
for i in T_list:
if i.joina
i.join()
T1.join()
T2.jion
然后产生需求,需要对于返回值进行判断。使用了以下的函数去get_result
class EnhancedThread(Thread):
def __init__(self, target, args):
super(EnhancedThread, self).__init__()
self.target = target
self.args = args
def run(self):
self.result = self.target(*self.args)
def get_result(self):
try:
return self.result
except Exception:
return -1
后来发现使用这个可能存在各种各样的问题,,需要手动的去start,单独的去包装修饰一个已有的类会显得特别的冗余,所以开始使用concurrent中的ThreadPoolExecutor去做多线程的操作。
通过executor = ThreadPoolExecutor(最大线程数)进行初始化。
然后利用submit将函数加入线程池并开始运行,
from concurrent.futures import ThreadPoolExecutor,as_completed
import time
def wait_and_print(wait_time):
time.sleep(wait_time)
print("Has wait for %d seconds"%wait_time)
if wait_time== 3:
return False
return True
def get_result(future):
return futrue.result()
def run():
executor = ThreadPoolExecutor()
task_list =[]
for i in range(4):
temp_process = executor.submit(wait_and_print,i)
task_list.append(temp_process)
for i in as_completed(task_list):
#res = i.result()
res=i.add_done_callback(get_result)
print("The res is % d" % res)
time.sleep(0.5)
executor.shutdown(wait=True)
run()
但是本人在实际使用中发现,运行到as_completed时可能会程序突然终止,程序在运行50次之后可能发生该现象,到现在也没有发现为啥。十分不解。十分疑惑。