一:进程:进程是操作系统结构的基础;是一个正在执行的程序;计算机中正在运行的程序实例;可以分配给处理器并由处理器执行的一个实体;由单一顺序的执行显示,一个当前状态和一组相关的系统资源所描述的活动单元
1.多进程
由于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 = ("alex",)) p_list.append(p) p.start() for i in p_list: p.join() #注意这个地方得到join,等到上面的所有执行完以后再执行最后的end print("end")
结果为:
hello alex Wed Oct 12 16:50:18 2016
hello alex Wed Oct 12 16:50:18 2016
hello alex Wed Oct 12 16:50:18 2016
end
2.类式调用
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()) #此时的self.name 是进程对象下的一个属性,是有名字的, 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")
结果为:
hello MyProcess-1 Wed Oct 12 16:59:27 2016
hello MyProcess-2 Wed Oct 12 16:59:27 2016
hello MyProcess-3 Wed Oct 12 16:59:27 2016
end
3.进程关系(父进程与子进程之间的关系)
from multiprocessing import Process import os import time def info(title): print(title) print("module name:",__name__) print("parent process:",os.getppid()) print("process id:",os.getpid()) def f(name): info("