线程池的概念:
使用concurrent模块进行并发编程的
先上简单的代码
import timefrom concurrent.futures import ThreadPoolExecutorfrom threading import current_threaddef func(i): print('thread',i,current_thread()) # 线程ID time.sleep(1) print('thread %s end'%i)tp = ThreadPoolExecutor(5) # 开了5个线程for i in range(20): tp.submit(func,i)tp.shutdown()print('主线程')
返回值
import timefrom concurrent.futures import ThreadPoolExecutorfrom threading import current_threaddef func(i): print('thread',i,current_thread()) # 线程ID time.sleep(1) print('thread %s end'%i) return i*'*'tp = ThreadPoolExecutor(5) # 实例化线程池,开了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())print('主线程')
回调函数
import osimport timefrom concurrent.futures import ProcessPoolExecutorfrom threading import current_thread as cthread# 线程池的回调函数 子线程完成的def func(i): print('thread',i,os.getpid()) time.sleep(1) print('thread %s end'%i) return i*'*'def call_back(arg): print('call back:',os.getpid()) print('ret:',arg.result())if __name__ == '__main__': tp = ProcessPoolExecutor(5) ret_l = [] for i in range(20): tp.submit(func,i).add_done_callback(call_back) print('主线程',os.getpid())
# 回调函数 # 在线程池中 由子线程完成的 # 在进程池中 由主线程完成的 # 线程池 # 实例化线程池 ThreadPoolExecutor 5*cpu_count # 异步提交任务 submit/map # 阻塞直到任务完成 shutdown # 获取子线程的返回值 result # 回调函数 add_down_callback