标签:pen event opened import lse int proc code 运行
创建进程两种方式
守护进程
进程对象.deamon 值为True的时候,表示新的子进程是一个守护进程,守护进程随着主进程代码色执行结束而结束。在start之前运行
进程锁
为了数据安全 事例:12306售票一个文件{"ticket":1},有1张票,有10个人过来买票,每个人都看到为1张票,抢票。
# 锁 # 火车票 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(‘\033[32m%s买到票了\033[0m‘%i) else: print(‘\033[31m%s没买到票\033[0m‘%i) time.sleep(0.1) with open(‘ticket‘,‘w‘) as f: json.dump(dic,f) lock.release() # 还钥匙 if __name__ == ‘__main__‘: # for i in range(10): # p = Process(target=show,args=(i,)) # p.start() lock = Lock() for i in range(10): p = Process(target=buy_ticket, args=(i,lock)) p.start()
标签:pen event opened import lse int proc code 运行
原文地址:https://www.cnblogs.com/oyoui/p/9012727.html