multiprocessing 多进程基本使用 示例代码1 import timeimport randomfrom multiprocessing import Processdef run(name): print(f'{name} is running') time.sleep(random.randint(1,3)) print(f'{name} is end')if __name__ =='__main__': p_lis
multiprocessing
多进程基本使用
- 示例代码1
import time import random from multiprocessing import Process def run(name): print(f'{name} is running') time.sleep(random.randint(1,3)) print(f'{name} is end') if __name__ =='__main__': p_list = [] for i in range(3): # 传参的两种方式 # p = Process(target=run,kwargs={'name':f'线程{i}'}) p = Process(target=run,args=(f"线程{i}",)) p_list.append(p) p.start() # for i in p_list: # p.join() # join后主进程会等待子进程都结束再结束 print('主进程结束') # strat():方法的功能 1.开启进程 2.执行功能
- 示例代码2
import os import time import random from multiprocessing import Process class Run(Process): def __init__(self,name): super().__init__() self.name = name def run(self): # 必须实现run方法 print(os.getppid(),os.getpid()) print(f'{self.name} is running') time.sleep(random.randint(1,3)) print(f'{self.name} is end') if __name__ =='__main__': p_list = [] for i in range(5): p = Run(f'线程{i}') p_list.append(p) p.start() for i in p_list: p.join() print('主进程结束',os.getpid())
进程池(from multiprocessing import Pool)
- 进程池原理
- 示例代码(串行)
import os import time from multiprocessing import Pool def task(n): print('{} is running'.format(os.getpid())) time.sleep(2) print('{} is done'.format(os.getpid())) return n**2 if __name__ == '__main__': # print(os.cpu_count()) #查看cpu个数 p = Pool(4) # 最大四个进程 for i in range(1,7): # 开7个任务 ret = p.apply(task,args=(i,)) #同步的,一个运行完才执行另一个 print(f'本次任务结束:{ret}') p.close() # 禁止往进程池内在添加任务 p.join() # 等待进程池 print('主进程')
- 示例代码(并行)
import os import time from multiprocessing import Pool def task(n): print('{} is running'.format(os.getpid())) time.sleep(2) print('{} is done'.format(os.getpid())) return n**2 if __name__ == '__main__': # print(os.cpu_count()) #查看cpu个数 ret_lis = [] p = Pool(4) # 最大四个进程 for i in range(1,7): # 开7个任务 ret = p.apply_async(task,args=(i,)) # 异步的,一个运行完才执行另一个 ret_lis.append(ret) p.close() # 禁止往进程池内在添加任务 p.join() # 等待进程池 # print('主进程') print(_.get() for _ in ret_lis)
更多参数请参考:https://www.cnblogs.com/damumu/p/7321732.html
线程池(from multiprocessing.dummy import Pool)
- 线程池的原理
- 线程池首先会维护一个任务队列
- 生成工作使用的线程(可以是自定义个数,也可以是系统默认)
- 线程分别从队列中取出任务,并执行,一个任务执行完成需要告诉主线程完成一个任务
- 再从任务队列中取出任务,直到所有任务为空,退出线程
- 示例代码
import requests from multiprocessing.dummy import Pool def get_source(url): ret = requests.get(url) return ret.text def main(): urls = [ # ..., # ..., # ..., ] pool = Pool(5) ret_list = pool.map(get_source, urls) pool.close() # 调用join之前,先调用close函数,否则会出错。执行完close后不会有新的线程加入到pool, # join函数等待所有子线程结束 pool.join() for ret in ret_list: print(ret) print('*'*100) # 更多关于dummy的介绍:https://my.oschina.net/zyzzy/blog/115096 if __name__ == '__main__': main()