042多进程

内容:进程创建(两种方法)

#############################
第一种创建方法:通过创建线程对象,参数设置进程执行的方法以及方法的参数

from multiprocessing import Process
import time

def f(name):
    time.sleep(0.2)
    print('hello',name,time.ctime())

if __name__ == '__main__':
    p_list = []
    for i in range(3):
        p = Process(target=f,args=('xxx',))
        p_list.append(p)
        p.start()
    for i in p_list:
        i.join()
    print('end')

#############################
第二种创建线程的方法:
1、创建类继承Process类
2、类里面覆盖run方法
3、创建对象,执行start方法开启线程

from multiprocessing import Process
import time
class MyProcess(Process):
    def __init__(self):
    super(MyProcess,self).__init__()

    def run(self):
        time.sleep(0.2)
        print('hello',self.name,time.ctime())

if __name__ == '__main__':
    p_list = []
    for i in range(3):
        p = MyProcess()
        p.start()
        p_list.append(p)
    for t in p_list:
        t.join()
    print('end')

# 运行结果:
# hello MyProcess-1 Sun Feb  4 09:19:07 2018
# hello MyProcess-2 Sun Feb  4 09:19:07 2018
# hello MyProcess-3 Sun Feb  4 09:19:07 2018
# end

self.name默认是进程启的名字,可以自己更改

 

posted @ 2018-03-13 15:25  Alos403  阅读(175)  评论(0编辑  收藏  举报