多进程相当于多开程序
一、fork,在Linux中可以使用,但很少用
ret = os.fork()
if ret == 0:
#子进程
else:
#父进程
二、multiprocessing
multiprocessing
模块就是跨平台版本的多进程模块
1、创建单个子进程方式:
from multiprocessing import Process
p1 = Process(target = xxx)
p1.start()
2、创建多个子进程往往用到进程池:
from multiprocessing import Pool
import os
import time
def worker(num):
for i in range(5):
print('===pid = %d ===num = %d==='% (os.getpid(),num))
time.sleep(1)
if __name__ == '__main__':
pool = Pool(3)#进程池中最大进程数
for i in range(10):
print('---%d---'%i)
#添加任务,如果任务数量超过了进程池中进程个数,
#未被执行的任务会在后面等待
pool.apply_async(worker,(i,))#非堵塞方式
pool.close()#关闭进程池,相当于不能够再次添加新任务
pool.join()#主进程 创建/添加 任务后,主进程默认不会等待进程池中的任务执行完才结束
#而是当主进程任务做完之后立刻结束,如果没有join,
#会导致进程池中任务不被执行
#拷贝文件demo
import os
from multiprocessing import Pool,Manager
def copyFile(name,oldName,newName,queue):
fr = open(oldName + '/' + name)
fw = open(newName + '/' + name,'w')
content = fr.read()
fw.write(content)
queue.put(name)
fr.close()
fw.close()
def main():
#获取文件夹名字
oldName = input('请输入文件夹的名字:')
#创建新的文件夹
newName = oldName + '复件'
os.mkdir(newName)
#拷贝文件放入新的文件夹
nameList = os.listdir(oldName)
pool = Pool(5)
queue = Manager().Queue()
for name in nameList:
pool.apply_async(copyFile,args = (name,oldName,newName,queue))
#获取拷贝进度
num = 0
allNames = len(nameList)
while True:
queue.get()
num += 1
copyRate = num/allNames
print(' 进度:%.2f %% '%(copyRate*100),end = '')
if num == allNames:
break
print('完成')
if __name__ == '__main__':
main()