python多进程

守护进程

守护进程其实就是**“子进程“是否伴随主进程一起结束**:守护==>伴随,即守护进程会伴随主进程的代码运行完毕后而死掉

进程:当父进程需要将一个任务并发出去执行,需要将该任务放到以个子进程里
守护:当该子进程内的代码在父进程代码运行完毕后就没有存在的意义了,就应该
将该子进程设置为守护进程,会在父进程代码结束后死掉

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from multiprocessing import Process
import time
def ():
print(123)
time.sleep(1)
print("end123")

def bar():
print(456)
time.sleep(3)
print("end456")

if __name__ == '__main__':
p1=Process(target=foo)
p2=Process(target=bar)


# 所以p1会在print("main-------")打印完成后死掉,所以p1进程不会打印
p1.daemon=True
p1.start()
p2.start()
# time.sleep(1)
print("main-------")

进程锁

主要使用multiprocessing下的Lock对象

就是将要执行任务的部门代码(只涉及到修改共享数据的代码)变成串行,作用是让进程不乱掉,下面代码就是可以避免 i 乱打印

1
2
3
4
5
6
7
8
9
10
11
12
13
from multiprocessing import Process, Lock

def f(l, i):
l.acquire() #锁住进程
try:
print('hello world', i)
finally:
l.release() #释放锁

if __name__ == '__main__':
lock = Lock()
for num in range(10):
Process(target=f, args=(lock, num)).start()

(理解为用锁来限制,同一时间只能让一个人拿着锁去改数据,先抢到锁的人
就有优先购买的权限)

1
2
3
4
# 主要就是用的这三个
lock = lock()
lock.acquire() # 拿钥匙,开门
lock.release() #还钥匙,关门

抢票demo

写法一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#模拟抢票软件的原理:
from multiprocessing import Lock,Process
import json,os,time,random

def check():
#查票功能实现并行访问
time.sleep(1)
with open('db.txt','rt',encoding='utf-8') as f:
dic=json.load(f)
print('%s 查看余票数为 %s'%(os.getpid(),dic['count']))

def get():
#购票因为牵涉到对后台数据的修改,所以加互斥锁目的是逐一进行访问修改,以免数据错乱
with open('db.txt', 'rt',encoding='utf-8') as f:
dic = json.load(f)
time.sleep(2)
if dic['count'] >0:
#有票
dic['count']-=1
time.sleep(random.randint(1, 3))
#在购票时,模拟网络延迟...
with open('db.txt', 'wt',encoding='utf-8') as f:
json.dump(dic,f)
print('%s 购票成功'%os.getpid())
else:
print('%s 没有余票'%os.getpid())

def task(mutex):
#查看(并行访问)
check()
#抢票(加入互斥锁,实现串行访问,先到先得原则)
mutex.acquire()
get()
mutex.release() #第一个购买完成后,解锁,后续进入继续购买


if __name__ == '__main__':
mutex=Lock() #调用Lock类拿到一个对象
for i in range(10):
p=Process(target=task,args=(mutex,))
p.start()

写法二:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# 锁

# 火车票
import json
import time
from multiprocessing import Process
from multiprocessing import Lock

def show(i):
with open('ticket') as f:
dic = json.load(f)
print('余票: %s'%dic['ticket'])

def buy_ticket(i,lock):
lock.acquire() #拿钥匙进门
with open('ticket') as f:
dic = json.load(f)
time.sleep(0.1)
if dic['ticket'] > 0 :
dic['ticket'] -= 1
print('