Python多进程
进程(与线程基本一致):multiprocessing 模块
进程 :一堆资源的集合;图片、文字、线程
1、创建、启动进程、进程锁
p = multiprocessing.Process(target=create_data,args=(1,)) #进程
p.start() #启动进程
multiprocessing.active_children() #进程数
lock = multiprocessing.Lock() #进程锁
import multiprocessing import threading import time # lock = multiprocessing.Lock() def create_data(number): print("data..",number) time.sleep(2) if __name__ == '__main__': for i in range(5): p = multiprocessing.Process(target=create_data,args=(1,)) #进程 p.start() while len(multiprocessing.active_children())!=1: #等待子进程 pass print("运行完成!")
2、进程池:
p = multiprocessing.Pool() #创建进程池;参数是进程池数,默认进程池数量是CPU的核心数
p.close() #关闭进程池
p.join() #等待子线程都执行完成
import multiprocessing import time import os qq_numbers = ["511402865","260303838","1099276647","1490768397","729226162", "1164019076","569380213","923296994","330547222","609924484","1054114694", "854795345"] def create_data(number): print("data..",number) time.sleep(2) if __name__ == '__main__': print(os.cpu_count()) p = multiprocessing.Pool() for qq in qq_numbers: p.apply_async(create_data,args=(qq,)) p.close() p.join() #等待子线程都执行完成 print("done!")