在Python中进程操作
multiprocessm模块
multiprocess.process模块
1 1 p.start():启动进程,并调用盖子进程的p.run()
2 2 p.run():进程启动时运行的方法,正是它去调用target指定的函数,我们自定义的类中一定要实现该方法
3 3 p.terminate():强制终止进程p,不会进行任何清理操作,如果p创建了子进程,该子进程就成了僵尸进程,使用该方法需要特别小心这种情况。如果p还保存了一个锁那么也将不会被释放,进而导致死锁
4 4 p.is_alive():如果p仍在运行,返回值为True
5 5 p.join():主进程等待p终止(强调:是主线程处于等的状态,而p是处于运行的状态)
p.daemon:默认值为False,如果设为True,代表p为后台运行的守护进程,当p的父进程终止时,p也随之终止,当p的父进程时,p也随之终止,并且设定为True后,p不能创建自己的新进程,必须在p.start()之前设置
p.name:进程的名称
os.getpid():进程的pid
1 import time
2 from mulitiprocessing import Process
3
4 def func(name):
5 print('hello',name)
6 time.sleep(1)
7
8 if __name__ == '__main__':
9 p_lst = []
10 for i in range(5):
11 p = Process(target=func,args=('yan',))
12 p.start()
13 p_lst.append(p)
14 p.join()
15 #for p in p_lst:p.join()
16 print('父进程在执行')
一些其他开启的进程方法,比如继承:
1 import os
2 from mulitiprocessing import Process
3
4 class MyProcess(Process):
5 def __init__(self,name):
6 super().__init__()
7 self.name = name
8 def func(self):
9 print(os.getpid)
10 print('%s 正在和漂亮妹子聊天' %self.name)
11
12 p1 = MyProcess('yan')
13 p2 = MyProcess('chou')
14 p3 = MyProcess('da')
15
16 p1.start()
17 p2.start()
18 p3.start()
19
20 p1.join()
21 p2.join()
22 p3.join()
23 print('主进程')
进程之间的数据隔离问题
import os
from multiprocessing import Process
def work():
global n
n = 0
print('子进程内:',n)
if __name__ == '__main__':
n = 100
p = Process(target = work)
p.start()
print('主进程内:',n)
守护进程
含义:会随着主进程的结束而结束
主进程创建守护进程的作用;
一、守护进程会在主进程代码执行结束后就终止
二、守护进程内无法再开启子进程,否则抛出异常:
注意:进城之间是互相独立的,主进程代码运行结束,守护进程随即结束
1 import time
2 import os
3 from multiprocessing import Process
4
5 class MyProcess(Process):
6 def __init__(self,person):
7 super().__init__()
8 self.person = person
9 def func(self):
10 print(os.getpid(),self.name)
11 print('%s正在和妹子聊天' %self.person)
12
13 p = MyProcess('大为')
14 p.daemon = True #一定要在p.start()前设置p为守护进程,禁止p创建子进程,并且父进程代执行结束,p即终止运行
15 p.start()
16 time.sleep(10)
17 print('主进程')
1 import time
2 from multiprocessing import Process
3
4 def func1():
5 while True:
6 time.sleep(0.2)
7 print('我还活着')
8
9 def func2():
10 time.sleep(2)
11 print('in func2 finihsh')
12
13 if __name__ == '__main__':
14 p1 = Process(target = func1)
15 p1.daemon = True
16 p1.start()
17 p2 = Process(target = func2)
18 p2.start()
19 i = 0
20 while i<3:
21 print('我是socket server')
22 time.sleep(1)
23 i +=1
socket聊天并发实例
1 import socket
2 from multiprocessing import Process
3
4 def server(conn):
5 ret = '你好'.encode('utf-8')
6 conn.send(ret)
7 msg = conn.recv(1024).decode('utf-8')
8 print(msg)
9 conn.close()
10 if __name == '__main__':
11 sk = socket.socket()
12 sk.bind(('127.0.0.1',8080))
13 sk.listen()
14 whlie True:
15 conn,addr = sk.accpet()
16 p = Process(target = server,args = (conn,))
17 p.start()
18 sk.close()
1 import socket
2 sk = socket.socket()
3 sk.connect(('127.0.0.1',8080))
4 msg = sk.recv(1024).decode('utf-8')
5 print(msg)
6
7 msg2 = input('>>>').encode('utf-8')
8 sk.send(msg2)
9
10 sk.close()