守护进程
守护进程其实就是**“子进程“是否伴随主进程一起结束**:守护==>伴随,即守护进程会伴随主进程的代码运行完毕后而死掉
进程:当父进程需要将一个任务并发出去执行,需要将该任务放到以个子进程里
守护:当该子进程内的代码在父进程代码运行完毕后就没有存在的意义了,就应该
将该子进程设置为守护进程,会在父进程代码结束后死掉
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.daemon=True p1.start() p2.start() 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() 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('
|
近期评论