zoukankan      html  css  js  c++  java
  • python ==》 并发编程之多进程

    1.什么是进程:

     回答: 正在进行的一个过程或者说一个任务,而 这个过程就叫做进程。

    1.1 进程与程序的区别:

     回答: 程序仅仅是一堆代码而已,而进程指的是程序的运行过程。

    2.并发与并行。

    回答:无论是并行还是并发,在用户看来都是 同时  运行的, 不管是进程还是线程,都只是一个任务而已,真实干活的是cpu,cpu来做这些任务,而一个cpu同一时刻只能运行一个任务。 

    2.1: 并发什么意思:

     回答:并发是伪并行,即看起来是同事运行。单个cpu+多道技术就可以实现并发。(并行也属于并发)

    2.2: 并行什么意思:

     回答:并行就是同时运行,只有具备多个cpu才能实行并行。

    3.同步 与 异步

    3.1什么是同步:

     同步执行:一个进程在执行某个任务是,另外一个进程必须等待其执行完毕,才能继续执行

     异步执行:一个进程在执行某个任务时,另外一个进程无需等待其执行完毕,就可以继续执行,当有消息返回时,系统会通知后者进行同步通信,

     打电话时就是同步通信,发短信时就是异步通信。

    一、python 并发编辑之多进程

    1.1multiprocessing  模块介绍

      python 中的多线程无法利用多核优势,如果想要充分地使用多核cpu的资源(os.cpu_count()查看),在python中大部分情况需要使用多进程。python提供了非常好用的多进程包,这个包是: multiprocessing.

      multiprocessing模块的功能众多:如  支持子进程、通信和共享数据、执行不同形式的同步,提供了Process、Queue、Pipe、Lock等组件。

      需要再次强调的一点是:与线程不用,进程没有任何共享状态,进程修改的数据,改动仅限于该进程内。

    1.2 Process 类的介绍:

    创建进程的类:

    Process ([group [, target [, name [, args [ , kwargs]]]]) ,由该类实例化得到的对象,表示一个子进程中的任务(尚未启动)
    
    
    强调:
    1.需要使用关键字的方式来指定参数
    2.args指定的为传给target函数的位置参数,是一个元组形式,必须有逗号。
    

    参数介绍:

    1。group:参数未使用,值始终为None
    2. target:表示调用对象,即 子进程要执行的任务
    3. args  : 表示调用对象的位置传参数元组, args = (1,2,“aray”,)
    4. kwargs:表示调用对象的字典,kwargs = {’name':'aray','age':18} 
    5.name : 为子进程的名称
    

    方法介绍:

    1 p.start():启动进程,并调用该子进程中的p.run() 
    2 p.run():进程启动时运行的方法,正是它去调用target指定的函数,我们自定义类的类中一定要实现该方法  
    3 p.terminate():强制终止进程p,不会进行任何清理操作,如果p创建了子进程,该子进程就成了僵尸进程,使用该方法需要特别小心这种情况。如果p还保存了一个锁那么也将不会被释放,进而导致死锁
    4 p.is_alive():如果p仍然运行,返回True
    5 p.join([timeout]):主线程等待p终止(强调:是主线程处于等的状态,而p是处于运行的状态)。timeout是可选的超时时间,需要强调的是,p.join只能join住start开启的进程,而不能join住run开启的进程  
    

    属性介绍:

    1 p.daemon:默认值为False,如果设为True,代表p为后台运行的守护进程,当p的父进程终止时,p也随之终止,并且设定为True后,p不能创建自己的新进程,必须在p.start()之前设置
    2 p.name:进程的名称
    3 p.pid:进程的pid 
    4 p.exitcode:进程在运行时为None、如果为–N,表示被信号N结束(了解即可) 
    5 p.authkey:进程的身份验证键,默认是由os.urandom()随机生成的32字符的字符串。这个键的用途是为涉及网络连接的底层进程间通信提供安全性,这类连接只有在具有相同的身份验证键时才能成功(了解即可) 
    

    1.3 Process 类的使用

              part1:创建并开启子进程的两种方式

    注意:在windows中Process()必须放到# if __name__ == '__main__':下

    Since Windows has no fork, the multiprocessing module starts a new Python process and imports the calling module.
    If Process() gets called upon import, then this sets off an infinite succession of new processes (or until your machine runs out of resources).
    This is the reason for hiding calls to Process() inside

    if __name__ == "__main__"
    since statements inside this if-statement will not get called upon import.

    由于Windows没有fork,多处理模块启动一个新的Python进程并导入调用模块。
    如果在导入时调用Process(),那么这将启动无限继承的新进程(或直到机器耗尽资源)。
    这是隐藏对Process()内部调用的原,使用if __name__ == “__main __”,这个if语句中的语句将不会在导入时被调用。

    方法一:
    import time
    import random
    from multiprocessing import  Process
    def piao(name):
        print('%s playing' %name)
        time.sleep(random.randint(1,3))
        print('%s playing end'%name)
    
    if __name__ == '__main__':
        p1 = Process(target=piao,args = ('aray',))  #必须加逗号
        p2 = Process(target=piao,args = ('zxc',))
        p3 = Process(target=piao,args = ('asd',))
        p4 = Process(target=piao,args = ('qwe',))
    
        p1.start()
        p2.start()
        p3.start()
        p4.start()
        print('主线程')
    
    输出结果“
    主线程
    aray playing
    zxc playing
    asd playing
    qwe playing
    aray playing end
    qwe playing end
    zxc playing end
    asd playing end
    
    
    方法二:
    import time
    import random
    from multiprocessing import Process
    
    class Piao(Process):
        def __init__(self,name):
            super().__init__()
            self.name = name
        def run(self):
            print('%s playing'%self.name)
            time.sleep((random.randint(1,3)))
            print('%s playing end'%self.name)
    
    if __name__ == '__main__':
    
        p1=Piao('aray')
        p2=Piao('zxc')
        p3=Piao('asd')
        p4=Piao('qwe')
        p1.start()
        p2.start()
        p3.start()
        p4.start()
        print('主进程')
    
    输出结果:
    主进程
    aray playing
    zxc playing
    asd playing
    qwe playing
    zxc playing end
    aray playing end
    asd playing end
    qwe playing end
    开启进程的方法

     练习:把  socket 通信编程并发的形式。

    服务端:
    from socket import *
    from multiprocessing import Process
    
    server = socket(AF_INET,SOCK_STREAM)
    server.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
    server.bind(('127.0.0.1',8080))
    server.listen(5)
    print('ready go')
    
    def talk(conn,addr):
        while True:
            try:
                msg = conn.recv(1024)
                if not msg: break
                conn.send(msg.upper())
                print('from client msg:%s'%msg)
            except Exception:
                break
    
    if __name__ == '__main__':
        while True:
            conn,client_addr =server.accept()
            p = Process(target=talk, args=(conn,client_addr))
            p.start()
    
    
    客户端:
    from socket import *
    
    client = socket(AF_INET,SOCK_STREAM)
    client.connect(('127.0.0.1',8080))
    
    while True:
        msg = input('>>:').strip()
        client.send(msg.encode('utf-8'))
        msg = client.recv(1024)
        print('from server %s'%msg.decode('utf-8'))
    View Code

             part2: Process对象的其他方法或属性

    #进程对象的其他方法1:iterminate,is_alive
    from multiprocessing import Process
    import time
    import random
    
    class Play(Process):
        def __init__(self,name):
            self.name = name
            super().__init__()
    
        def run(self):
            print('%s is playing ' %self.name)
            time.sleep(random.randint(1,3))
            print('%s play end'%self.name)
    
    if __name__ == '__main__':
    
        p1 = Play('aray')
        p1.start()
    
        p1.terminate()   #关闭进程,不会立即关闭,所以is_alive立刻查看的结果可能还是存活
        print(p1.is_alive())
        print('开始')
        time.sleep(3)
        print(p1.is_alive())
    
    
    输出结果:
    True
    开始
    False
    
    #进程对象的其他方法2: p,daemon = True,p.join
    from multiprocessing import Process
    import time
    import random
    
    class Play(Process):
        def __init__(self,name):
            # self.name =name
            super().__init__()#Process的__init__方法会执行self.name=Piao-1,所以加到这里,会覆盖我们的self.name=name
            self.name = name  #为我们开启的进程设置名字的做法
        def run(self):
            print('%s is playing '%self.name)
            time.sleep(random.randint(1,3))
            print('%s is paly end'%self.name)
    
    if __name__ == '__main__':
        p = Play('aray')
        p.daemon =True  #一定要在p.start()前设置,设置p为守护进程,禁止p创建子进程,并且父进程死,p跟着一起死
        p.start()
        p.join(1)  #等待p停止,等1秒就不再等了
        print('开始')
        print(p.pid)  #查看pid
    
    输出结果:
    aray is playing 
    开始
    20892
    

    1.互斥锁 也 称 同步锁:Lock()

    一:没加锁之前
    import os
    import time
    from multiprocessing import Process
    def work():
    
        print('task[%s] is running '%os.getpid())
        time.sleep(3)
        print('task[%s] is done'%os.getpid())
    
    if __name__ == '__main__':
        p1 = Process(target=work,)
        p2 = Process(target=work,)
        p3 = Process(target=work,)
        p1.start()
        p2.start()
        p3.start()
        print('主公')
    
    输出结果:
    主公
    task[13768] is running 
    task[22400] is running 
    task[21128] is running 
    task[13768] is done
    task[22400] is done
    task[21128] is done
    
    Process finished with exit code 0
    
    
    二、加锁之后
    import os
    import time
    from multiprocessing import Process,Lock
    def work(mutex):
        mutex.acquire()
        print('task[%s] is running '%os.getpid())
        time.sleep(3)
        print('task[%s] is done'%os.getpid())
        mutex.release()
    if __name__ == '__main__':
        mutex=Lock()
        p1 = Process(target=work,args=(mutex,))
        p2 = Process(target=work,args=(mutex,))
        p3 = Process(target=work,args=(mutex,))
        p1.start()
        p2.start()
        p3.start()
        print('主公')
    
    输出结果:
    主公
    task[6700] is running 
    task[6700] is done
    task[21140] is running 
    task[21140] is done
    task[14584] is running 
    task[14584] is done
    
    Process finished with exit code 0
    互斥锁

    2.守护进程:daemon

    import os
    import time
    from multiprocessing import Process
    def work():
        print('task[%s] is running '%os.getpid())
        # time.sleep(1)
        print('task[%s] is done'%os.getpid())
    
    if __name__ == '__main__':
        p1 = Process(target=work)
        p2 = Process(target=work)
        p3 = Process(target=work)
        p1.daemon = True   #守护进程
        p2.daemon = True   #守护进程
        p3.daemon = True   #守护进程 
        p1.start()
        p2.start()
        p3.start()
        # time.sleep(2)
        print('')
    
    输出结果:
    主
    守护进程

    3.主进程等待机制:join()

    import os
    import time
    from multiprocessing import Process,Lock
    def work(mutex):
        mutex.acquire()
        print('task[%s] 洗衣服 '%os.getpid())
        time.sleep(3)
        print('task[%s] 晒衣服'%os.getpid())
        mutex.release()
    def work2(mutex):
        mutex.acquire()
        print('task[%s] 煮饭 '%os.getpid())
        time.sleep(3)
        print('task[%s] 炒菜'%os.getpid())
        mutex.release()
    def work3(mutex):
        mutex.acquire()
        print('task[%s] 下电影 '%os.getpid())
        time.sleep(3)
        print('task[%s] 看电影'%os.getpid())
        mutex.release()
    if __name__ == '__main__':
        mutex=Lock()
        p1 = Process(target=work,args=(mutex,))
        p2 = Process(target=work2,args=(mutex,))
        p3 = Process(target=work3,args=(mutex,))
        p1.start()
        p2.start()
        p3.start()
        # p1,p2,p3.join()
        p1.join()
        p2.join()
        p3.join()
        print('')
    
    输出结果:
    task[22592] 洗衣服 
    task[22592] 晒衣服
    task[17328] 煮饭 
    task[17328] 炒菜
    task[23072] 下电影 
    task[23072] 看电影
    主
    
    Process finished with exit code 0
    主进程等待机制

    4.强制关闭:terminate()

    import os
    import time
    from multiprocessing import Process,Lock
    def work(mutex):
        mutex.acquire()
        print('task[%s] is running '%os.getpid())
        time.sleep(3)
        print('task[%s] is done'%os.getpid())
        mutex.release()
    if __name__ == '__main__':
        mutex=Lock()
        p1 = Process(target=work,args=(mutex,))
        # p2 = Process(target=work,args=(mutex,))
        # p3 = Process(target=work,args=(mutex,))
        p1.start()
        # p2.start()
        # p3.start()
        p1.terminate()
        time.sleep(3)
        print(p1.is_alive())
        print(p1.name)
        print(p1.pid)
    
    输出结果:
    False
    Process-1
    22888
    
    Process finished with exit code 0
    强制关闭进程

    5.进程队列:Queue

    from multiprocessing import Process,Queue
    
    q = Queue(4)   #设置 4 个进程
    q.put('first',)
    q.put('second',)
    q.put('third',)
    q.put('fourth',block=True)   #block  默认为True。如果队列不足4就在那等待。
    
    print(q.get())
    print(q.get())
    print(q.get())
    print(q.get())
    
    输出结果:
    first
    second
    third
    fourth
    
    Process finished with exit code 0
    进程队列

    练习:

    抢票:

    import json
    import os
    import random
    from multiprocessing import Process,Lock
    
    #查询票数
    def search():
        dic = json.load(open('db.txt')) #打开文件 并且 序列化
        print('剩余票数:%s '%dic['count'])
    
    #购票
    def get_ticket():
        dic = json.load(open('db.txt'))
        if dic['count'] > 0:
            dic['count'] -=1
            time.sleep(random.randint(1,3))
            json.dump(dic,open('db.txt','w'))
            print('购买成功: %s'%os.getpid())
    
    #运行调用
    def task(mutex):     
        search()
        mutex.acquire()
        get_ticket()
        mutex.release()    
    
    if __name__ == '__ main __':
        mutex = Lock()
        for i in range(5):
            p = Process(target = task , args = (mutex,))
            p.start()
    
    输出结果: (这里  db.txt  里面的  count  值为  1.就一张票)
    剩余票数:1
    剩余票数:1
    剩余票数:1
    剩余票数:1
    剩余票数:1
    购买成功:13176
    
    Process finished with exit code 0
    购票

    多消费者和多生产者:

    import os 
    import random
    import time
    from multiprocessing import Process,JoinableQueue
    
    def producer_bun(q): #生产包子
        for i in range(5):
            time.sleep(2)  #睡2s  让它能有时间响应
            res = ' 包子 %s' %i
            q.put(res)
            print('%s 制造了 %s' %(os.getpid(),res))
        q.join()
    
    def producer_sticks(q):  #生产油条
        for i in range(5):
            time.sleep(2):
            res = '油条 %s' % i 
            q.put(res)
            print('%s 制造了 %s',%(os.getpid(),res))
        q.join()
    
    def consumer(q):  #消费者
        while True:
            res  = q.get()
            time.sleep(random.randint(1,3))
            print('%s 吃了 %s'%(os.getpid(),res))
            q.task_done()
    
    if __name__ == '__main__':
        q= JoinableQueue()
        p1 = Process(target = prodcuer_bun, args = (q,))    #生产者1
        p2 = Process(target = producer_sticks,args = (q,))  #生产者2
      
        p3 = Process(target = consumer, args = (q,))    #消费者1
        p4 = Process(target = consumer, args = (q,))    #消费者2
    
        p3.daemon = True          #守护进程
        p4.daemon = True          #守护进程
        p_l = [p1,p2,p3,p4]
        for p in p_l:
            p.start()
        p1.join()
        p2.join()
        print('')
    
    输出结果:
    3392 制造了 包子0
    20628 制造了 油条0
    8180 吃了 包子0
    15756 吃了 油条0
    3392 制造了 包子1
    20628 制造了 油条1
    15756 吃了 油条1
    3392 制造了 包子2
    20628 制造了 油条2
    8180 吃了 包子1
    15756 吃了 包子2
    3392 制造了 包子3
    20628 制造了 油条3
    8180 吃了 油条2
    3392 制造了 包子4
    8180 吃了 油条3
    20628 制造了 油条4
    15756 吃了 包子3
    15756 吃了 油条4
    8180 吃了 包子4
    主
    
    Process finished with exit code 0
    View Code

     开启进程的两种方法:

    #继承调用:
    import time
    import random
    from multiprocessing import Process
    
    class Piao(Process):
        def __init__(self,name):
            super().__init__()
            self.name = name
        def run(self):
            print('%s playing'%self.name)
            time.sleep((random.randint(1,3)))
            print('%s playing end'%self.name)
    
    if __name__ == '__main__':
    
        p1=Piao('aray')
        p2=Piao('zxc')
        p3=Piao('asd')
        p4=Piao('qwe')
        p1.start()
        p2.start()
        p3.start()
        p4.start()
        print('主进程')
    
    输出结果:
    主线程
    aray playing
    zxc playing
    asd playing
    qwe playing
    aray playing end
    asd playing end
    qwe playing end
    zxc playing end
    
    Process finished with exit code 0
    
    
    直接调用:
    import time
    import random
    from multiprocessing import  Process
    def piao(name):
        print('%s playing' %name)
        time.sleep(random.randint(1,3))
        print('%s playing end'%name)
    
    if __name__ == '__main__':
        p1 = Process(target=piao,args = ('aray',))  #必须加逗号
        p2 = Process(target=piao,args = ('zxc',))
        p3 = Process(target=piao,args = ('asd',))
        p4 = Process(target=piao,args = ('qwe',))
    
        p1.start()
        p2.start()
        p3.start()
        p4.start()
        print('主线程')
    
    输出结果:
    主线程
    aray playing
    zxc playing
    asd playing
    qwe playing
    aray playing end
    asd playing end
    qwe playing end
    zxc playing end
    
    Process finished with exit code 0
    View Code

    通过进程池和回调函数,完成一个爬虫网页的案例:

    from multiprocessing import Pool
    import requests
    import os
    
    def get_page(url):
        print('%s  get  %s'%(os.getpid(),url))
        response = requests.get(url)
        return {'url':url,'text':response.text}
    
    def parse_page(res):
        print('%s  parse %s'%(os.getpid(),res['url']))
        with open('db.txt','a') as f:
            parse_res = 'url : %s size: %s 
     ' %(res['url'],len(res['text']))
            f.write(parse_res)
    
    
    if __name__ == '__main__':
        p = Pool(4)
        urls = [
            'https://www.baidu.com',
            'http://www.openstack.org',
            'https://www.python.org',
            'https://help.github.com/',
            'http://www.sina.com.cn/'
        ]
    
        for url in urls:
            p.apply_async(get_page,args=(url,),callback=parse_page)  #callback 回调函数
    
        p.close()
        p.join()
        print('',os.getpid())
    View Code
  • 相关阅读:
    testNG 注解使用说明
    jenkins 生成HTML报表,邮件推送
    Jenkins 邮件发送
    Jenkins+SVN+Maven+testNG管理项目
    SVN 安装教程
    大数据笔记(十一)——倒排索引
    大数据笔记(十)——Shuffle与MapReduce编程案例(A)
    大数据笔记(九)——Mapreduce的高级特性(B)
    大数据笔记(八)——Mapreduce的高级特性(A)
    大数据笔记(七)——Mapreduce程序的开发
  • 原文地址:https://www.cnblogs.com/zhongbokun/p/7428614.html
Copyright © 2011-2022 走看看