多进程模块:multiprocessing

多进程:

(1) 前面我们学习的多线程,其实算不上真正的多线程,即使你开了很多个线程,在同一时间内只能有一个CPU核数来处理一个线程
(2) 在 python 中,多进程算得上是真正的多线程,假设你的CPU有四核,如果开四个子进程,四个CPU核数会同时处理这四个子进程
(3) 在 threading 中,我们是通过 threading.Thread(target=function, args=(....)) 来创建一个对象,然后再通过对象的 start() 方法来运行一个子线程,多个子线程可以并发执行
(4) 在 multiprocessing 中,我们是通过 multiprocessing.Process(target=function, args=(....)) 来创建一个对象,然后再通过对象的 start() 方法来运行一个子进程,多个子进程可以并发执行

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import os
import time
import multiprocessing

def fun():
    print 'hello world', os.getpid(), os.getppid()
    time.sleep(1)

for i in range(10):
    p = multiprocessing.Process(target=fun, args=())
    p.start()
[root@localhost ~]$ python 1.py 
hello world 4056 4055
hello world 4057 4055
hello world 4058 4055
hello world 4059 4055
hello world 4060 4055
hello world 4061 4055
hello world 4062 4055
hello world 4063 4055
hello world 4064 4055
hello world 4065 4055

 
multiprocessing 进程池:

(1) 当我们只需要几个或十几个多进程时,可以用 multiprocessing.Process() 来创建,但如果我们需要几百或几千个子进程同时并发运行时还用这种方法就不可取了
(2) 我们可以创建一个进程池,进程池会自动创建一个新的子进程来执行请求,multiprocessing 提供了 Pool 这个类来实现创建进程池
(3) 进程池里可以设置最大可创建的子进程数,当有新的请求提交到 pool 中时,如果池还没有满,那么就会创建一个新的进程用来执行该请求;
(4) 但如果池中的进程数已经达到规定最大值,那么该请求就会等待,直到池中有进程结束,才会创建新的进程来它。

    pool = multiprocessing.Pool(processes=4)    创建一个进程池,processes 可以指定进程池里可以创建的最大子进程数,设置成跟CPU核数一致即可
    pool.apply_async(func=...., args=(....))    向进程池提交请求,进程池会自动创建一个新的进程来处理该请求,如果提交的请求超过最大可创建的进程数就会被阻塞,处于等待状态
    pool.close()    关闭进程池,会等待池中的请求执行完才关闭
    pool.terminate()    关闭进程池,会直接关闭,即使池中还有请求在执行
    pool.join()    阻塞主进程,防止子线程还没执行完程序就退出了,必须用在 pool.close() 后面

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import os
import time
import multiprocessing

def hello():
    print 'hello world', time.ctime() 
    time.sleep(1)

if __name__ == '__main__':
    pool = multiprocessing.Pool(processes=2)
    for i in range(6):
        pool.apply_async(func=hello, args=())
    pool.close()
    pool.join()
    print 'Done!'
[root@localhost ~]$ vim 1.py    
[root@localhost ~]$ python 1.py 
hello world Tue Jan 29 05:27:45 2019
hello world Tue Jan 29 05:27:45 2019
hello world Tue Jan 29 05:27:46 2019
hello world Tue Jan 29 05:27:46 2019
hello world Tue Jan 29 05:27:47 2019
hello world Tue Jan 29 05:27:47 2019
Done!

      

猜你喜欢

转载自www.cnblogs.com/pzk7788/p/10355787.html