立即学习:/course/play/24458/296451?utm_source=blogtoedu
进程池与线程池:
一般应用在网站上,进程池或线程池最大的数量一般需要尽可能地大但是不要超出服务器的承载范围
1.进程池:
1)concurrent.futures.ProcessPoolExecutor(n)
2)创建了一个进程池,池中含有n个进程,任务都由这n个进程来完成
3)n默认为cpu的核数
4)pool.shutdown():表示关闭了新提交任务给进程池的入口,且等待进程池执行结束后再进行后面的代码
from concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor#进程池与线程池import os,random,timedef processpool(name):print('pid:%s ; %s:running'%(os.getpid(),name))time.sleep(random.randint(2,5))if __name__ == '__main__':pool = ProcessPoolExecutor(5)#创建一个进程池,池子里面有5个进程for i in range(10):pool.submit(processpool,'任务%s'%i)pool.shutdown(wait=True)print('zhu')
运行结果:由结果可知,进程的pid只有5个,10个任务一直都是由这5个进程来完成
'''"F:\software install\python3.6.4\python.exe" C:/Users/jinlin/Desktop/python_further_study/并发编程/进程池线程池.pypid:11848 ; 任务0:runningpid:13740 ; 任务1:runningpid:12848 ; 任务2:runningpid:7196 ; 任务3:runningpid:10884 ; 任务4:runningpid:11848 ; 任务5:runningpid:13740 ; 任务6:runningpid:12848 ; 任务7:runningpid:7196 ; 任务8:runningpid:10884 ; 任务9:runningzhu进程已结束,退出代码0'''
2.线程池
1)concurrent.futures.ThreadPoolExecutor(n)
2)创建了一个线程池,池中含有n个线程,任务都由这n个线程来完成
3)pool.shutdown():表示关闭了新提交任务给线程池的入口,且等待线程池执行结束后再进行后面的代码
from concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor#进程池与线程池from threading import currentThreadimport os,random,timedef processpool(name):print('%s pid:%s ; %s:running'%(currentThread().getName(),os.getpid(),name))time.sleep(random.randint(2,5))if __name__ == '__main__':pool = ThreadPoolExecutor(5)#创建一个进程池,池子里面有5个进程for i in range(10):pool.submit(processpool,'任务%s'%i)pool.shutdown()print('zhu')
运行结果:由结果可以知道,线程池的所有线程的pid都是一样的,那是因为线程池中的线程都是在同一个进程中,因此pid会一致,且只有5个线程在执行任务
'''"F:\software install\python3.6.4\python.exe" C:/Users/jinlin/Desktop/python_further_study/并发编程/进程池线程池.pyThreadPoolExecutor-0_0 pid:11888 ; 任务0:runningThreadPoolExecutor-0_1 pid:11888 ; 任务1:runningThreadPoolExecutor-0_2 pid:11888 ; 任务2:runningThreadPoolExecutor-0_3 pid:11888 ; 任务3:runningThreadPoolExecutor-0_4 pid:11888 ; 任务4:runningThreadPoolExecutor-0_3 pid:11888 ; 任务5:runningThreadPoolExecutor-0_2 pid:11888 ; 任务6:runningThreadPoolExecutor-0_1 pid:11888 ; 任务7:runningThreadPoolExecutor-0_4 pid:11888 ; 任务8:runningThreadPoolExecutor-0_0 pid:11888 ; 任务9:runningzhu进程已结束,退出代码0'''