python基础:多进程讲解

fork的使用方法:

import os 
import time

# 主进程执行到os.fork()会产生一个子进程。ret>0,代表主进程;ret=0,代表子进程
ret=os.fork() # 从这句开始,父进程和子进程都会执行以下的代码
print(ret)
if ret>0:
    print('---父进程--{}-'.format(os.getpid))
    time.sleep(1)
else:
    print('---子进程-{}-{}-'.format(os.getpid,os.getppid()))
    time.sleep(1)

note:fork只能在linux平台下使用,其他平台没有该方法。

  全局变量在多个进程中不共享:

g_num=100

ret=os.fork()
if ret==0:
    g_num+=1
    print('process-1 g_num={}'.format(g.num)) # 输出 101
else:
    time.sleep(3)
    print('process-2 g_num={}'.format(g.num)) # 输出 100

 multiprocessing模块的使用(具有跨平台特性)

方法一:创建一个Process对象

from multiprocessing import Process
import time

def test():
    while True:
        print('test')
        time.sleep(1)

if __name__=='__main__':

    p=Process(target=test)
    p.start() # 开启一个进程
    p.join() # 等待该进程运行结束

方法二:创建一个类继承Process类,并重写run方法

from multiprocessing import Process
import time

class MyProcess(Process):

    def run(self):
        while True:
            print('my process')
            time.sleep(1)
            
if __name__=='__main__':
    p=MyProcess()
    p.start()
    
    while True:
        print('main')
        time.sleep(1)

使用进程池Pool

# -*- coding:utf-8 -*-
from multiprocessing import Pool
import os
import random
import time

def worker(num):
    for i in range(5):
        print('pid={} num={}'.format(os.getpid(),num))
        time.sleep(1)
        
if __name__=='__main__':
    pool=Pool(3)
    for i in range(10):
        print('---{}---'.format(i))
        pool.apply_async(worker,(i,))
        
    
    pool.close() # 
    pool.join() # 等待pool中所有子进程结束

 进程间通信Queue,多进程拷贝文件。

# -*- coding:utf-8 -*-
from multiprocessing import Pool,Manager
import os
import random
import time

def copyFileTask(filename,oldFolderName,newFolderName,queue):
    
    with open(os.path.join(oldFolderName,filename),'r') as fr:
    
        print(os.path.join(oldFolderName,filename))
        content=fr.read()
        
        with open(os.path.join(newFolderName,filename),'w') as fw:
        
            print(os.path.join(newFolderName,filename))
            fw.write(content)
    
    queue.put(filename)
    
        
def main():
    # 0. 获取用户要copy的文件夹的名字
    oldFolderName=input("请输入文件夹的名字:")

    # 1. 创建一个文件夹
    newFolderName=oldFolderName+"-副本"
    os.mkdir(newFolderName)

    # 2. 获取old文件夹中的所有的文件名字
    filenames=os.listdir(oldFolderName)

    # 3. 使用多进程的方式copy所有文件
    pool=Pool(5)
    q=Manager().Queue()
    
    for filename in filenames:
        pool.apply_async(copyFileTask,args=(filename,oldFolderName,newFolderName,q))
    
    pool.close()
    pool.join()
    
    num=0
    allNum=q.qsize()
    while not q.empty():
        q.get()
        num+=1
        copyRate=num/allNum
        print('\rcopy的进度是:{:.2f}%'.format(copyRate*100))
        
if __name__=='__main__':
    main()

 

posted @ 2017-12-28 00:56  blackx  阅读(617)  评论(0编辑  收藏  举报