多进程调用

由于GIL的存在,Python很多时候并不能真正多线程并发,为了利用CPU资源,可以使用多进程

进程模块:multiprocessing

from multiprocessing  import Process
import time

def f(name):
    time.sleep(2)
    print("hello",name,time.ctime())

if __name__ == '__main__':
    l = []
    for i in range(5):
        p = Process(target=f,args=("ss",))
        l.append(p)
        p.start()

    for i in l:
        i.join()

继承调用

from multiprocessing import Process
import time

class MyProcess(Process):
    def __init__(self):
        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()
     p.start() p_list.append(p)
for p in p_list: p.join() print('end')

 和线程不同的地方:

p.daemon =True:守护进程是做为一个属性,直接调用
posted @ 2019-06-12 00:21  saber゛  Views(191)  Comments(0Edit  收藏  举报