# 抢票的例子 import json from multiprocessing import Process, Lock import time def search_ticket_num(i): with open('ticket.txt', encoding='utf-8') as f: ticket = json.load(f) print(f"{i}号查询到当前的余票是{ticket['count']}张") def pay_ticket(i): with open('ticket.txt', encoding='utf-8') as f: ticket = json.load(f) if ticket['count'] > 0: ticket['count'] -= 1 print(f"{i}号买到了一张票") time.sleep(0.1) with open('ticket.txt', encoding='utf-8', mode='w') as f2: json.dump(ticket, f2) def get_ticket(i, lock): search_ticket_num(i) with lock: # 代替acquire和release,更加方便和安全 pay_ticket(i) if __name__ == '__main__': lock = Lock() # 实例化一个锁对象 for i in range(10): Process(target=get_ticket, args=(i, lock)).start()
互斥锁:
from multiprocessing import Lock # 互斥锁: # 即同一个进程中连续acquire多次 lock = Lock() lock.acquire() print(1) lock.acquire() print(2)