什么是python 进程锁?
#同步效率低,但是保证了数据安全 重点
很多时候,我们需要在多个进程中同时写一个文件,如果不加锁机制,就会导致写文件错乱
这个时候,我们可以使用multiprocessing.Lock()
def get_ticket(i,ticket_lock): print("等待大家都到齐") time.sleep(1) ticket_lock.acquire() with open("ticket","r")as f: # for line in f: # dic=json.load(line.strip()) dic=json.load(f) if dic["count"]>0: time.sleep(random.random()) dic["count"]-=1 with open("ticket","w")as s_f: json.dump(dic,s_f) print("%s号抢到票了"%i) else: print("%s号没抢到票,明年见" % i) ticket_lock.release() if __name__ == '__main__': ticket_lock=Lock() for i in range(1,11): p=Process(target=get_ticket,args=(i,ticket_lock,)) p.start()
什么是信号量?
# 红绿灯事件 import time import random from multiprocessing import Event,Process def cars(e,i): if not e.is_set(): print('car%i在等待'%i) e.wait() # 阻塞 直到得到一个 事件状态变成 True 的信号 print('\033[0;32;40mcar%i通过\033[0m' % i) def light(e): while True: if e.is_set():#判断事件状态 e.clear() print('\033[31m红灯亮了\033[0m') else: e.set() print('\033[32m绿灯亮了\033[0m') time.sleep(2) if __name__ == '__main__': e = Event() traffic = Process(target=light,args=(e,)) traffic.start() for i in range(20): car = Process(target=cars, args=(e,i)) car.start() time.sleep(random.random())
事件
# coding:utf-8 import threading import time event = threading.Event() def chihuoguo(name): # 等待事件,进入等待阻塞状态 print '%s 已经启动' % threading.currentThread().getName() print '小伙伴 %s 已经进入就餐状态!'%name time.sleep(1) event.wait() # 收到事件后进入运行状态 print '%s 收到通知了.' % threading.currentThread().getName() print '小伙伴 %s 开始吃咯!'%name # 设置线程组 threads = [] # 创建新线程 thread1 = threading.Thread(target=chihuoguo, args=("a", )) thread2 = threading.Thread(target=chihuoguo, args=("b", )) # 添加到线程组 threads.append(thread1) threads.append(thread2) # 开启线程 for thread in threads: thread.start() time.sleep(0.1) # 发送事件通知 print '主线程通知小伙伴开吃咯!' event.set()
Thread-1 已经启动 小伙伴 a 已经进入就餐状态! Thread-2 已经启动 小伙伴 b 已经进入就餐状态! 主线程通知小伙伴开吃咯! Thread-1 收到通知了. 小伙伴 a 开始吃咯! Thread-2 收到通知了. 小伙伴 b 开始吃咯!
队列:
import time def girl(q): print(q.get()) print(q.get()) def boy(q): q.put("约吗") if __name__ == '__main__': q=Queue boy_p=Process(target=boy,args=(q,)) girl_p=Process(target=girl,args=(q,)) boy_p.start() girl_p.start() time.sleep(1) q.put("好好工作")
相关操作
from multiprocessing import Queue q=Queue(3) q.put(1) # print(q.full()) q.put(2) # print(q.full()) q.put(3) # print(q.full()) print(q.get()) # print(q.empty()) print(q.get()) # print(q.empty()) print(q.get()) # print(q.empty()) # q.get_nowait()#queue.Empty # try: # q.get(False)#queue.Empty # except: # print("队列为空!") # while 1: # try: # q.get(False) # queue.Empty # except: # print("队列为空!")