多线程pool补充
在python中没有办法使用队列进行传入到pool中
这就导致如果要使用传入队列,那么需要使用另外的封装方法
使用pool和队列模拟文件复制
import random
import time
from multiprocessing import Manager
from multiprocessing import Pool
def my_copy_read(q,old_file):
# 打开文件将文件内容读取出来
with open(old_file,'r',encoding='utf-8') as f:
q.put(f.readlines()) # 将文件内容读到队列中
# print(f'文件{old_file}读取完成')
def my_copy_write(q,new_file):
time.sleep(random.random()*2) # 随机0-2秒钟
# 从队列中拿出数据并写入新的文件
with open(new_file,'w',encoding='utf-8') as f:
f.writelines(q.get())
# 文件写入完成后输出
print(f'新文件{new_file}写入完成')
if __name__ == '__main__':
# 实例化队列
q = Manager().Queue()
# 实例化进程池,并设置进程池只允许有3个进程同时执行
pool = Pool(2)
# 准备好文件路径列表
old_file_address = [f'./study{i}.py' for i in range(1,8)]
# 准备好新的文件路径列表
for i in old_file_address:
pool.apply_async(my_copy_read,(q,i))
# 写文件
for i in range(1,len(old_file_address)+1):
pool.apply_async(my_copy_write,(q,f'./{i}.txt'))
pool.close()
pool.join()
print('总进程结束')
使用的是from multiprocessing import Manager,在Manager上面存在Manager().Queue()实例化一个队列,这个队列的使用和常规的Queue方法是一样的,同样具有get和put方法,
这里本身./路径下存在7个文件,将文件复制到当前目录下并改名