线程池concurrent.futures模块
用concurrent.futures模块开一个线程池
import time from threading import currentThread from concurrent.futures import ThreadPoolExecutor def func(i): time.sleep(1) # currentThread().ident查看线程id print('子线程%s' % i, currentThread().ident) # 开启线程池 tp = ThreadPoolExecutor(5) for i in range(20): # 提交任务 tp.submit(func, i) # 关闭线程池 tp.shutdown()
map方法
import time from threading import currentThread from concurrent.futures import ThreadPoolExecutor def func(i): time.sleep(1) print('子线程%s' % i, currentThread().ident) tp = ThreadPoolExecutor(5) tp.map(func, range(20))
用concurrent.futures模块开一个进程池
import time import os from concurrent.futures import ProcessPoolExecutor def func(i): time.sleep(1) # currentThread().ident查看线程id print('子进程%s' % i, os.getpid()) if __name__ == '__main__': # 开启线程池 tp = ProcessPoolExecutor(5) for i in range(20): # 提交任务 tp.submit(func, i) # 关闭线程池 tp.shutdown()
使用result获取子线程中的返回值
import time from threading import currentThread from concurrent.futures import ThreadPoolExecutor def func(i): time.sleep(1) print('子线程%s' % i,currentThread().ident) return i**2 tp = ThreadPoolExecutor(5) ret_l = [] for i in range(20): ret = tp.submit(func, i) ret_l.append(ret) for ret in ret_l: print(ret.result())
使用回调函数来处理子线程中代码的执行结果
import time from threading import currentThread from concurrent.futures import ThreadPoolExecutor def func(i): time.sleep(1) print('子线程%s' % i, currentThread().ident) return i**2 def callback(ret): print(ret.result()) tp = ThreadPoolExecutor(5) for i in range(20): tp.submit(func, i).add_done_callback(callback) tp.shutdown()

浙公网安备 33010602011771号