python-进程补充和线程理论

2022/1/15 7:08:29

本文主要是介绍python-进程补充和线程理论,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

image

僵尸进程与孤儿进程

僵尸进程
进程代码运行结束之后并没有直接结束而是需要等待收回子进程资源才能结束。
孤儿进程
主进程已经死亡(非正常)但是子进程还在运行

守护进程

守护某个进程,一旦这个进程结束那么也随之结束
from multiprocessing import Process
import time


def judy(name):
	print('%s is working ' % name)
	time.sleep(1)
	print('%s finished her work')


if __name__ == '__main__':
	p = Process(target=judy, args=('judy',))
	p.daemon = True  ### 这个命令是将开启的进程变成主进程的守护进程
	p.start()
	print('who is first')

互斥锁

在并发的情况下,如果操作同一份数据的话,极其容易造成数据错乱,那么只有将并发变成串行,虽然降低了效率但是提升了数据安全。

举个例子:

import json
from multiprocessing import Process


def check(name):
	with open(r'test.txt', 'r', encoding='utf8') as f:
		data_dict = json.load(f)
		cat_number = data_dict['cat']
		print('%s查看了余票,还有:%s张' % (name, cat_number))


def buy(name):
	with open(r'test.txt', 'r', encoding='utf8') as f:
		data_dict = json.load(f)
		cat_number = data_dict['cat']
		if cat_number > 0:
			cat_number -= 1
			data_dict['cat'] = cat_number
			with open(r'test.txt', 'w', encoding='utf8') as f:
				json.dump(data_dict, f)
				print('%s 抢到了票,余票剩余 %s' % (name, cat_number))
		else:
			print('没有票了没有票了')


def run(name):
	check(name)
	buy(name)


if __name__ == '__main__':
	for i in range(2):
		p = Process(target=run,args=(i,))
		p.start()

结果:

image
所以这样是不行的,必须得加上互斥锁!!

正确的版本应该是这样的!!!!!

import json
from multiprocessing import Process, Lock


def check(name):
	with open(r'test.txt', 'r', encoding='utf8') as f:
		data_dict = json.load(f)
		cat_number = data_dict['cat']
		print('%s查看了余票,还有:%s张' % (name, cat_number))


def buy(name):
	with open(r'test.txt', 'r', encoding='utf8') as f:
		data_dict = json.load(f)
		cat_number = data_dict['cat']
		if cat_number > 0:
			cat_number -= 1
			data_dict['cat'] = cat_number
			with open(r'test.txt', 'w', encoding='utf8') as f:
				json.dump(data_dict, f)
				print('%s 抢到了票,余票剩余 %s' % (name, cat_number))
		else:
			print('没有票了没有票了')


def run(name, mutex):
	check(name)
	mutex.acquire()
	buy(name)
	mutex.release()


if __name__ == '__main__':
	mutex = Lock() #在主进程里面产生锁
	for i in range(2):
		p = Process(target=run, args=(i, mutex)) ###要把锁穿进去!!!!
		p.start()

结果

image


	


这篇关于python-进程补充和线程理论的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程