zoukankan      html  css  js  c++  java
  • 多进程

    参考资料:

    https://www.cnblogs.com/jiangfan95/p/11439207.html

    https://www.jianshu.com/p/a5f10c152c20

    python中的多线程无法利用多核优势,如果想要充分地使用多核CPU的资源,在python中大部分情况需要使用多进程。Python提供了multiprocessing。

    multiprocessing模块用来开启子进程,并在子进程中执行我们定制的任务(比如函数),multiprocessing模块的功能众多:支持子进程、通信和共享数据、执行不同形式的同步,提供了Process、Queue、Pipe、Lock等组件。

    实现的效果:

    1.父进程的结束不会影响子进程。

    2.父进程等待所有子进程结束后再结束。

    创建并开启子进程的方法

    第一、直接创建

    import time
    import random
    from multiprocessing import Process
    def run(name):
        print('%s runing' %name)
        time.sleep(random.randrange(1,5))
        print('%s running end' %name)
    
    p1=Process(target=run,args=('anne',)) #必须加,号 
    p2=Process(target=run,args=('alice',))
    
    p1.start()
    p2.start()
    
    第二、继承
    import time
    import random
    from multiprocessing import Process
    
    
    class Run(Process):
        def __init__(self,name):
            super().__init__()
            self.name=name
        def run(self):
            print('%s runing' %self.name)
            time.sleep(random.randrange(1,5))
            print('%s runing end' %self.name)
    
    p1=Run('anne')
    p2=Run('alex')
    p3=Run('ab')
    p4=Run('hey')
    p1.start() #start会自动调用run
    p2.start()
    p3.start()
    p4.start()
  • 相关阅读:
    Restful levels &HATEOAS基本介绍~
    跨源资源共享(CORS)概念、实现(用Spring)、起源介绍
    Ubuntu下math库函数编译时未定义问题的解决
    常用软件清单~
    JetBrains PyCharm 专业版激活
    hello1.java内容简单介绍
    hello1 web项目中web.xml作用分析
    hello2 source analisis(notes)
    Servlet filter
    分析helo1项目中的 Web.xml
  • 原文地址:https://www.cnblogs.com/howmanyk/p/14384001.html
Copyright © 2011-2022 走看看