一、进程
1、什么是进程
(1)正在进行的一个过程或者说一个任务,而负责执行的就是CPU
2、进程与程序的区别
(1)程序仅仅是一堆代码而已,而进程指的是程序的运行过程
同一个程序执行两次,也是两个进程
3.同步与异步
(1)同步执行:一个程序在执行时,另一个程序等执行完后才能执行
异步执行:一个程序执行时,另一个程序无需等待执行完毕才执行,就可以继续执行,当有消息返回时系统会通知后者进行处理
这样可以提高执行效率。
4.并行与并发
(1)无论是并行还是并发,在用户看来都是'同时'运行的,不管是进程还是线程,都只是一个任务而已,真是干活的是cpu,cpu来做这些任务,而一个cpu同一时刻只能执行一个任务
5.进程:
from multiprocessing import Process import time ,random def piao(name): print('%s is piaoing'%name) time.sleep(random.randint(1,3)) print('%s is end'%name) if __name__ == '__main__': p1=Process(target=piao,args=('fu',)) p1.start() print('主进程')
from multiprocessing import Process import time,random import os class Piao(Process): def __init__(self,name): super().__init__() self.name=name def run(self): print(os.getppid(),os.getpid()) print('%s is piaoing'%self.name) time.sleep(random.randint(5,10)) print('%s is piao end'%self.name) if __name__ == '__main__': p1=Piao('fu') p2=Piao('ping') # p1=Process(target=piao,args=('fu',)) p1.start() p2.start() print('主进程',os.getppid(),os.getpid())
from multiprocessing import Process import time,random import os class Piao(Process): def __init__(self,name): super().__init__() self.name=name def run(self): print(os.getppid(),os.getpid()) time.sleep(1000) if __name__ == '__main__': p1=Piao('al') p2=Piao('wu') p3=Piao('yu') p1.start() p2.start() p3.start() print('主进程',os.getpid(),os.getppid())
from multiprocessing import Process import time,random import os def piao(name): print(os.getppid(),os.getpid()) print('%s is piaoing' %name) # time.sleep(random.randint(1,3)) print('%s is piao end' %name) if __name__ == '__main__': p1=Process(target=piao,kwargs={'name':'alex',}) p2=Process(target=piao,args=('wupeiqi',)) p3=Process(target=piao,kwargs={'name':'yuanhao',}) p1.start() p2.start() p3.start() print('主进程',os.getpid())
from multiprocessing import Process import time,random import os class Piao(Process): def __init__(self,name): super().__init__() self.name=name def run(self): print(os.getppid(),os.getpid()) print('%s is piaoing' %self.name) # time.sleep(random.randint(1,3)) print('%s is piao end' %self.name) if __name__ == '__main__': p1=Piao('alex') p2=Piao('wupeiqi') p3=Piao('yuanhao') p1.start() p2.start() p3.start() print('主进程',os.getpid(),os.getppid())