python 进程复习

时间:2022-04-02 03:53:38
import os
import time
ret = os.fork() # 创建子线程 if ret ==0: # 子进程中返回值为0,父进程>0
while True:
print('......1......')
time.sleep(1) else:
while True:
print('......2......')
time.sleep(1)

python 进程复习

多fork问题,以下代码会出现4个进程

import os
import time
ret = os.fork() if ret ==0:
print('......1......') else:
print('......2......') ret = os.fork() if ret ==0:
print('......11......') else:
print('......22.....')

python 进程复习

python 进程复习

import os
import time
ret = os.fork() if ret ==0:
print('......1......') else:
print('......2......') ret = os.fork() if ret ==0:
print('......11......') else:
print('......22.....')

python 进程复习

python 进程复习

进程间通信

进程之间默认无关联

普通进程间通信用 Queue队列

进程池中用Manager().Queue()

q.qsize()

q.full()

q.empty()

q.put()

q.get()

q.put_nowait()

q.get_nowait()

多进程文件拷贝案例

from multiprocessing import Pool,Manager
import os def copyFileName(name,oldFolderName,newFolderName,queue):
'完成copy一个文件的功能'
fr = open(oldFolderName + '/' + name)
fw = open(newFolderName + '/' + name,'w') content = fr.read()
fw.write(content) fr.close()
fw.close() queue.put(name) def main(): # 0,获取永远要copy的文件夹名字
oldFolderName = input('请输入文件夹的名字:') # 1.创建一个文件夹
newFolderName = oldFolderName + '-复件'
os.mkdir(newFolderName) # 2.获取old文件夹中所有文件的名字
fileNames = os.listdir(oldFolderName) # 3.使用多进程的方式copy原文件夹中所有文件到新的文件夹中
pool = Pool(5) #创建队列,计数
queue = Manager().Queue() for name in fileNames:
pool.apply_async(copyFileName,args=(name,oldFolderName,newFolderName,queue)) num = 0
allNum = len(fileNames)
while num<allNum:
queue.get()
num += 1
copyRate = num/allNum
print('\rcopy的进度是:%.2f%%'%(copyRate*100),end='') print('\n已完成拷贝。。。。。') if __name__ == '__main__':
main()