• 【Rollo的Python之路】Python 多进程 学习笔记 multiprocessing


    Python 多进程:

    由于GIL的存在,python中的多线程并不是真正的多线程,如果想要充分地使用多核CUP的资源,在python里面大部分情况需要使用多进程,Python提供了非常好的多进程包multiprocessing.

    只需要定义一个函数,Python会完成其他所有的事情。

    import time
    from multiprocessing import Process
    
    def f(name):
        time.sleep(1)
        print("hello",name,time.ctime())
    
    if __name__ == "__main__":
        p_list=[]
        for i in range(3):
            p = Process(target=f,args=('rollo',))
            p_list.append(p)
            p.start()
    
        for p in p_list:
            p.join()
        print('end')

    用面向对象的方法创建多进程:

    from multiprocessing import Process
    import time
    
    class MyProcess(Process):
        def __init__(self):
            super(MyProcess,self).__init__()
    
        def run(self):
            time.sleep(1)
            print('hello',self.name,time.ctime())  #self.name 进程名,在Process类里面已经定义好了,也可以修改的。
    
    if __name__ == '__main__':
        p_list = []
    
        for i in range(3):
            p = MyProcess()
            p.start()
            p_list.append(p)
    
        for p in p_list:
            p.join()
    
        print('end')

    修改进程名:self.name

    from multiprocessing import Process
    import time
    
    class MyProcess(Process):
        def __init__(self,name):
            super(MyProcess,self).__init__()
            self.name = name
    
        def run(self):
            time.sleep(1)
            print('hello',self.name,time.ctime())  #self.name 进程名,在Process类里面已经定义好了,也可以修改的。
    
    if __name__ == '__main__':
        p_list = []
    
        for p in range(3):
            p = MyProcess('123')
            p.start()
            p2 = MyProcess('456')
            p2.start()
            p_list.append(p)
    
        for p in p_list:
            p.join()
    
        print('end')
  • 相关阅读:
    洛谷 P2986 [USACO10MAR]伟大的奶牛聚集Great Cow Gat…(树规)
    STREAMING #5 题解 3.高位网络
    冲刺NOIP2015提高组复赛模拟试题(五) 3.破坏基地
    冲刺NOIP2015提高组复赛模拟试题(五)2.道路修建
    冲刺NOIP2015提高组复赛模拟试题(五)1.数学作业
    洛谷P1186 玛丽卡 spfa+删边
    清北学堂 day6 花
    清北学堂 day6 兔子
    C++ STL 全排列函数
    flash分区的意义
  • 原文地址:https://www.cnblogs.com/rollost/p/10970475.html
Copyright © 2020-2023  润新知