- Python多进程Pool与Process主要区别
(1)Process需要自己管理进程,起一个Process就是起一个新进程;
(2)Pool是进程池,它可以开启固定数量的进程,然后将任务放到一个池子里,系统来调度多进程执行池子里的任务;
Python中多进程主要是通过multiprocessing实现的,通过私有函数all查看,需带双下划线;
import multiprocessing
multiprocessing.all
[‘Array’, ‘AuthenticationError’, ‘Barrier’, ‘BoundedSemaphore’, ‘BufferTooShort’, ‘Condition’, ‘Event’, ‘JoinableQueue’, ‘Lock’, ‘Manager’, ‘Pipe’, ‘Pool’, ‘Process’, ‘ProcessError’, ‘Queue’, ‘RLock’, ‘RawArray’, ‘RawValue’, ‘Semaphore’, ‘SimpleQueue’, ‘TimeoutError’, ‘Value’, ‘active_children’, ‘allow_connection_pickling’, ‘cpu_count’, ‘current_process’, ‘freeze_support’, ‘get_all_start_methods’, ‘get_context’, ‘get_logger’, ‘get_start_method’, ‘log_to_stderr’, ‘set_executable’, ‘set_forkserver_preload’, ‘set_start_method’]
再看库里面Process函数的定义:
class Process(object):
def __init__(self, group=None, target=None, name=None, args=(), kwargs={}):
self.name = ''
self.daemon = False
self.authkey = None
self.exitcode = None
self.ident = 0
self.pid = 0
self.sentinel = None
def run(self):
pass
def start(self):
pass
def terminate(self):
pass
def join(self, timeout=None):
pass
def is_alive(self):
return False
进程创建:Process(target=主要运行的函数,name=自定义进程名称可不写,args=(参数))
方法:is_alive():判断进程是否存活
join([timeout]):子进程结束再执行下一步,timeout为超时时间,有时进程遇到阻塞,为了程序能够运行下去而设置超时时间
run():如果在创建Process对象的时候不指定target,那么就会默认执行Process的run方法
start():启动进程,区分run()
terminate():终止进程,关于终止进程没有这么简单,貌似用psutil包会更好,有机会以后了解更多再写下。
其中,Process以start()启动某个进程。
属性:authkey: 在文档中authkey()函数找到这么一句话:Set authorization key of process设置过程的授权密钥 ,目前没找到相关应用实例,这个密钥是怎么用的呢?文章不提
daemon:父进程终止后自动终止,且自己不能产生新进程,必须在start()之前设置<