Bootstrap

Python 多线程高效处理任务

import concurrent.futures

def a(i):
    print(i)
    time.sleep(10)
    return True

def threding_test():
	result_list = []
	with concurrent.futures.ProcessPoolExecutor() as executor:
	   futures = [executor.submit(a, i) for i range(10)]
	   with tqdm(total=len(futures), desc=f"Please wait a moment... ") as pbar:
	       for future in concurrent.futures.as_completed(futures):
	           result = future.result()
	           if result is not None:
	               result_list.append(result)
	           pbar.update(1)
return result_list

if __name__ == '_main_':
threding_test()

Python 2不兼容concurrent.futures 可以使用future
python -m pip install futures

from concurrent.futures import ThreadPoolExecutor
def threding_test():
	result_list = []
	with ThreadPoolExecutor() as executor:
	   futures = [executor.submit(a, i) for i range(10)]
	   for future in futures :
	       result = future.result()
	       if result is not None:
            result_list.append(result)
return result_list
;