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')
  • 相关阅读:
    VMware Workstation 15 安装教程
    Kail更新源、输入法、浏览器
    Kali Linux 下载、引导、安装
    dwr超时
    jsp获取web的跟路径
    java线程安全
    jsp快速回顾
    在web.xml中可以设置jsp标签吗?
    axis2--生成的wsdl文件方法的参数问题
    java删除文件
  • 原文地址:https://www.cnblogs.com/qiujichu/p/10359120.html
Copyright © 2011-2022 走看看