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')

 

posted @ 2019-02-10 20:32  奶茶喝不胖  阅读(923)  评论(0编辑  收藏  举报