zoukankan      html  css  js  c++  java
  • python创建进程的两种方式

    线程内的任务不会同时执行,可以解决的方法是在每个进程里面执行一个线程,可以实现。(GIL的限制)

    multiprocessing管理进程的包,threading.Thread用来管理线程

    进程可以解决并发,但是相关的消息无法交互,需要借助别的例如Pipe和Queue(但是在使用的时候仍有资源的消耗)

    进程的创建方式一:函数式

    from multiprocessing import Process
    # 导入创建进程需要的包
    
    import  time
    
    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=('alvin',))
            p_list.append(p)
            p.start()
        for i in p_list:
            p.join()
        print('end')
    
    结果如下
    hello alvin Sun Feb 10 12:32:54 2019
    hello alvin Sun Feb 10 12:32:54 2019
    hello alvin Sun Feb 10 12:32:54 2019
    end

    进程创建方式二: 类

    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())
    
    if __name__=='__main__':
        p_list=[]
        for i in range(3):
            p=MyProcess('jiao')
            p.start()
            p_list.append(p)
        for p in p_list:
            p.join()
        print('end')
  • 相关阅读:
    直线型一阶倒立摆5---硬件平台搭建
    PE view---重要参数--C语言实现
    A1132. Cut Integer
    A1131. Subway Map (30)
    A1130. Infix Expression
    A1129. Recommendation System
    A1128. N Queens Puzzle
    A1127. ZigZagging on a Tree
    A1126. Eulerian Path
    A1125. Chain the Ropes
  • 原文地址:https://www.cnblogs.com/qiujichu/p/10359120.html
Copyright © 2011-2022 走看看