多进程(multiprocessing模块)
一 多进程的概念
multiprocessing
is a package that supports spawning processes using an API similar to the threading
module. The multiprocessing
package offers both local and remote concurrency,effectively side-stepping the Global Interpreter Lock by using subprocesses instead of threads. Due to this, the multiprocessing
module allows the programmer to fully leverage multiple processors on a given machine. It runs on both Unix and Windows.
由于GIL的存在,python中的多线程其实并不是真正的多线程,如果想要充分地使用多核CPU的资源,在python中大部分情况需要使用多进程。Python提供了非常好用的多进程包multiprocessing,只需要定义一个函数,Python会完成其他所有事情。借助这个包,可以轻松完成从单进程到并发执行的转换。multiprocessing支持子进程、通信和共享数据、执行不同形式的同步,提供了Process、Queue、Pipe、Lock等组件。
multiprocessing包是Python中的多进程管理包。与threading.Thread类似,它可以利用multiprocessing.Process对象来创建一个进程。该进程可以运行在Python程序内部编写的函数。该Process对象与Thread对象的用法相同,也有start(), run(), join()的方法。此外multiprocessing包中也有Lock/Event/Semaphore/Condition类 (这些对象可以像多线程那样,通过参数传递给各个进程),用以同步进程,其用法与threading包中的同名类一致。所以,multiprocessing的很大一部份与threading使用同一套API,只不过换到了多进程的情境。
但在使用这些共享API的时候,我们要注意以下几点:
- 在UNIX平台上,当某个进程终结之后,该进程需要被其父进程调用wait,否则进程成为僵尸进程(Zombie)。所以,有必要对每个Process对象调用join()方法 (实际上等同于wait)。对于多线程来说,由于只有一个进程,所以不存在此必要性。
- multiprocessing提供了threading包中没有的IPC(比如Pipe和Queue),效率上更高。应优先考虑Pipe和Queue,避免使用Lock/Event/Semaphore/Condition等同步方式 (因为它们占据的不是用户进程的资源)。
- 多进程应该避免共享资源。在多线程中,我们可以比较容易地共享资源,比如使用全局变量或者传递参数。在多进程情况下,由于每个进程有自己独立的内存空间,以上方法并不合适。此时我们可以通过共享内存和Manager的方法来共享资源。但这样做提高了程序的复杂度,并因为同步的需要而降低了程序的效率。
Process.PID中保存有PID,如果进程还没有start(),则PID为None。
进程间默认数据不共享
window系统下,需要注意的是要想启动一个子进程,必须加上那句if __name__ == "main",进程相关的要写在这句下面。
实例:
from multiprocessing import Process import time def f(name): time.sleep(1) print('hello', name,time.ctime()) if __name__ == '__main__': p_list=[] for i in range(3): p = Process(target=f, args=('alvin',)) p_list.append(p) p.start() for i in p_list: p.join() print('end')
类式调用
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 from multiprocessing import Process 2 import time 3 4 class MyProcess(Process): 5 def __init__(self): 6 super(MyProcess, self).__init__() 7 #self.name = name 8 9 def run(self): 10 time.sleep(1) 11 print ('hello', self.name,time.ctime()) 12 13 14 if __name__ == '__main__': 15 p_list=[] 16 for i in range(3): 17 p = MyProcess() 18 p.start() 19 p_list.append(p) 20 21 for p in p_list: 22 p.join() 23 24 print('end')
To show the individual process IDs involved, here is an expanded example:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 from multiprocessing import Process 2 import os 3 import time 4 def info(title): 5 print(title) 6 print('module name:', __name__) 7 print('parent process:', os.getppid()) 8 print('process id:', os.getpid()) 9 10 11 def f(name): 12 info('\033[31;1mfunction f\033[0m') 13 print('hello', name) 14 15 if __name__ == '__main__': 16 info('\033[32;1mmain process line\033[0m') 17 time.sleep(100) 18 p = Process(target=info, args=('bob',)) 19 p.start() 20 p.join()
注:os.getpid() 得到当前进程的进程号
os.getppid() 得到当前进程的父进程号
二 Process类
构造方法:
Process([group [, target [, name [, args [, kwargs]]]]])
group: 线程组,目前还没有实现,库引用中提示必须是None;
target: 要执行的方法;
name: 进程名;
args/kwargs: 要传入方法的参数。
实例方法:
is_alive():返回进程是否在运行。
join([timeout]):阻塞当前上下文环境的进程程,直到调用此方法的进程终止或到达指定的timeout(可选参数)。
start():进程准备就绪,等待CPU调度
run():strat()调用run方法,如果实例进程时未制定传入target,这star执行t默认run()方法。
terminate():不管任务是否完成,立即停止工作进程
属性:
authkey
daemon:和线程的setDeamon功能一样
exitcode(进程在运行时为None、如果为–N,表示被信号N结束)
name:进程名字
pid:进程号
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import time 2 from multiprocessing import Process 3 4 def foo(i): 5 time.sleep(1) 6 print (p.is_alive(),i,p.pid) 7 time.sleep(1) 8 9 if __name__ == '__main__': 10 p_list=[] 11 for i in range(10): 12 p = Process(target=foo, args=(i,)) 13 #p.daemon=True 14 p_list.append(p) 15 16 for p in p_list: 17 p.start() 18 # for p in p_list: 19 # p.join() 20 21 print('main process end')
二 进程间通讯
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 Queue: 2 linux: 3 q = multiprocessing.Queue() 4 5 def task(arg,q): 6 q.put(arg) 7 8 def run(): 9 for i in range(10): 10 p = multiprocessing.Process(target=task, args=(i, q,)) 11 p.start() 12 13 while True: 14 v = q.get() 15 print(v) 16 17 run() 18 windows: 19 def task(arg,q): 20 q.put(arg) 21 22 if __name__ == '__main__': 23 q = multiprocessing.Queue() 24 for i in range(10): 25 p = multiprocessing.Process(target=task,args=(i,q,)) 26 p.start() 27 while True: 28 v = q.get() 29 print(v) 30 31 Manager:(*) 32 Linux: 33 m = multiprocessing.Manager() 34 dic = m.dict() 35 36 def task(arg): 37 dic[arg] = 100 38 39 def run(): 40 for i in range(10): 41 p = multiprocessing.Process(target=task, args=(i,)) 42 p.start() 43 44 input('>>>') 45 print(dic.values()) 46 47 if __name__ == '__main__': 48 49 run() 50 windows: 51 def task(arg,dic): 52 time.sleep(2) 53 dic[arg] = 100 54 55 if __name__ == '__main__': 56 m = multiprocessing.Manager() 57 dic = m.dict() 58 59 process_list = [] 60 for i in range(10): 61 p = multiprocessing.Process(target=task, args=(i,dic,)) 62 p.start() 63 64 process_list.append(p) 65 66 while True: 67 count = 0 68 for p in process_list: 69 if not p.is_alive(): 70 count += 1 71 if count == len(process_list): 72 break 73 print(dic)
不同进程间内存是不共享的,要想实现两个进程间的数据交换,可以用以下方法:
Queues
使用方法跟threading里的queue类似:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 from multiprocessing import Process, Queue 2 3 def f(q,n): 4 q.put([42, n, 'hello']) 5 6 if __name__ == '__main__': 7 q = Queue() 8 p_list=[] 9 for i in range(3): 10 p = Process(target=f, args=(q,i)) 11 p_list.append(p) 12 p.start() 13 print(q.get()) 14 print(q.get()) 15 print(q.get()) 16 for i in p_list: 17 i.join()
Pipes
The Pipe()
function returns a pair of connection objects connected by a pipe which by default is duplex (two-way). For example:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 from multiprocessing import Process, Pipe 2 3 def f(conn): 4 conn.send([42, None, 'hello']) 5 conn.close() 6 7 if __name__ == '__main__': 8 parent_conn, child_conn = Pipe() 9 p = Process(target=f, args=(child_conn,)) 10 p.start() 11 print(parent_conn.recv()) # prints "[42, None, 'hello']" 12 p.join()
The two connection objects returned by Pipe()
represent the two ends of the pipe. Each connection object has send()
and recv()
methods (among others). Note that data in a pipe may become corrupted if two processes (or threads) try to read from or write to the same end of the pipe at the same time. Of course there is no risk of corruption from processes using different ends of the pipe at the same time.
A manager object returned by Manager()
controls a server process which holds Python objects and allows other processes to manipulate them using proxies.
A manager returned by Manager()
will support types list
, dict
, Namespace
, Lock
, RLock
, Semaphore
, BoundedSemaphore
, Condition
, Event
, Barrier
, Queue
, Value
and Array
. For example,
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 from multiprocessing import Process, Manager 2 3 def f(d, l,n): 4 d[n] = '1' 5 d['2'] = 2 6 d[0.25] = None 7 l.append(n) 8 print(l) 9 10 if __name__ == '__main__': 11 with Manager() as manager: 12 d = manager.dict() 13 14 l = manager.list(range(5)) 15 p_list = [] 16 for i in range(10): 17 p = Process(target=f, args=(d, l,i)) 18 p.start() 19 p_list.append(p) 20 for res in p_list: 21 res.join() 22 23 print(d) 24 print(l)
三 进程同步
Without using the lock output from the different processes is liable to get all mixed up.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 from multiprocessing import Process, Lock 2 3 def f(l, i): 4 l.acquire() 5 try: 6 print('hello world', i) 7 finally: 8 l.release() 9 10 if __name__ == '__main__': 11 lock = Lock() 12 13 for num in range(10): 14 Process(target=f, args=(lock, num)).start()
四 进程池
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import time 2 from concurrent.futures import ProcessPoolExecutor 3 4 def task(arg): 5 time.sleep(2) 6 print(arg) 7 8 if __name__ == '__main__': 9 10 pool = ProcessPoolExecutor(5) 11 for i in range(10): 12 pool.submit(task,i)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import requests 2 from bs4 import BeautifulSoup 3 from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor 4 5 6 # 模拟浏览器发送请求 7 # 内部创建 sk = socket.socket() 8 # 和抽屉进行socket连接 sk.connect(...) 9 # sk.sendall('...') 10 # sk.recv(...) 11 12 def task(url): 13 print(url) 14 r1 = requests.get( 15 url=url, 16 headers={ 17 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36' 18 } 19 ) 20 21 # 查看下载下来的文本信息 22 soup = BeautifulSoup(r1.text,'html.parser') 23 #print(soup.text) 24 content_list = soup.find('div',attrs={'id':'content-list'}) 25 for item in content_list.find_all('div',attrs={'class':'item'}): 26 title = item.find('a').text.strip() 27 target_url = item.find('a').get('href') 28 print(title,target_url) 29 30 def run(): 31 pool = ThreadPoolExecutor(5) 32 for i in range(1,50): 33 pool.submit(task,'https://dig.chouti.com/all/hot/recent/%s' %i) 34 35 36 if __name__ == '__main__': 37 run()
进程池内部维护一个进程序列,当使用时,则去进程池中获取一个进程,如果进程池序列中没有可供使用的进进程,那么程序就会等待,直到进程池中有可用进程为止。
进程池中有两个方法:
- apply
- apply_async
-
1 from multiprocessing import Process,Pool 2 import time 3 4 def Foo(i): 5 time.sleep(2) 6 return i+100 7 8 def Bar(arg): 9 print('-->exec done:',arg) 10 11 pool = Pool(5) 12 13 for i in range(10): 14 pool.apply_async(func=Foo, args=(i,),callback=Bar) 15 #pool.apply(func=Foo, args=(i,)) 16 17 print('end') 18 pool.close() 19 pool.join()