python 多进程 (并行编程 11)

2019-07-30 10:20:23 浏览数 (1)

import multiprocessing

def foo(i): print('called function in process %s' % i) if name=="main": pros=[] for i in range(5): p=multiprocessing.Process(target=foo,args=(i,)) pros.append(p) p.start() p.join()

线程和进程性能

import multiprocessing import datetime import threading def foo(i): print('called function in process %s' % i) if name=="main": pros=[] starttime = datetime.datetime.now() for i in range(5): p=multiprocessing.Process(target=foo,args=(i,)) pros.append(p) p.start() p.join() endtime = datetime.datetime.now() print((endtime - starttime).microseconds/1000) starttime = datetime.datetime.now() for i in range(5): p = threading.Thread(target=foo, args=(i,)) pros.append(p) p.start() p.join() endtime = datetime.datetime.now() print((endtime - starttime).microseconds / 1000)

called function in process 0 called function in process 1 called function in process 2 called function in process 3 called function in process 4 99.059 called function in process 0 called function in process 1 called function in process 2 called function in process 3 called function in process 4 0.998

获取CPU数量:multiprocessing.cpu_count()

import multiprocessing import time

def process(num): time.sleep(num) print('Process:', num)

if name == 'main': for i in range(5): p = multiprocessing.Process(target=process, args=(i,)) p.start()

代码语言:javascript复制
print('CPU number:'   str(multiprocessing.cpu_count()))
for p in multiprocessing.active_children():
    print('Child process name: '   p.name   ' id: '   str(p.pid))

print('Process Ended')

继承Process

from multiprocessing import Process import time

class MyProcess(Process): def init(self, loop): Process.init(self) self.loop = loop

代码语言:javascript复制
def run(self):
    for count in range(self.loop):
        time.sleep(1)
        print('Pid: '   str(self.pid)   ' LoopCount: '   str(count))

if name == 'main': for i in range(2, 5): p = MyProcess(i) p.start()

daemon=True 守护进程在主进程结束马上终止,如果daemon=False ,主进程结束也不会结束

from multiprocessing import Process import time import os

def func(num): print(f'{num},pid:{os.getpid()},ppid:{os.getppid()}') while True: print('is alive') time.sleep(0.5)

def wahaha(): i = 0 while i < 5: i = 1 print(f'第{i}秒') time.sleep(1)

if name == 'main': Process(target=wahaha).start() #子进程在主进程结束后仍然正常执行 p = Process(target=func,args=(1,)) p.daemon = True #主进程结束,该守护进程结束 p.start() time.sleep(3) print(f'pid:{os.getpid()},ppid:{os.getppid()}') print('主进程结束')

p.terminate() 进程终止

0 人点赞