并发安全问题
def task(name): print('%s is running' % name) time.sleep(3) if __name__ == '__main__': obj = Process(target=task, args=('egon',)) obj.daemon=True #守护进程必须在子进程开始前设置 obj.start() # 发送信号给操作系统 print('主')
父进程交给了子进程一个任务,任务还没有完成父进程就结束了,子进程就没有继续执行的意义了
互斥锁
互斥锁是为了保证多进程在调用统一资源时不会产生数据错乱的机制。
解决多进程同时操作一个资源产生错乱的方法有两个
1.加join:
def task1(): print('task1:aaa') time.sleep(random.randint(1,3)) print('task1:aa1') time.sleep(random.randint(1, 3)) print('task1:aa3') def task2(): print('task2:bbb') time.sleep(random.randint(1, 3)) print('task2:bb1') time.sleep(random.randint(1, 3)) print('task2:bb3') time.sleep(random.randint(1, 3)) def task3(): print('task3:ccc') time.sleep(random.randint(1, 3)) print('task:cc1') time.sleep(random.randint(1, 3)) print('task3:cc3') time.sleep(random.randint(1, 3)) if __name__ == '__main__': p1=Process(target=task1,args=(mutex,)) p2=Process(target=task2,args=(mutex,)) p3=Process(target=task3,args=(mutex,)) p1.start() p1.join(2) 在进程开始时加入join等待上一个进程对数据操作完成后再开始下一进程对数据的操作 p2.start() p2.join(2) p3.start()
本质上是吧多进程变成单进程来避免多个进程同时操作一个数据的情况
mutex=Lock() def task1(lock): lock.acquire() print('task1:aaa') time.sleep(random.randint(1,3)) print('task1:aa1') time.sleep(random.randint(1, 3)) print('task1:aa3') lock.release() def task2(lock): lock.acquire() print('task2:bbb') time.sleep(random.randint(1, 3)) print('task2:bb1') time.sleep(random.randint(1, 3)) print('task2:bb3') time.sleep(random.randint(1, 3)) lock.release() def task3(lock): lock.acquire() print('task3:ccc') time.sleep(random.randint(1, 3)) print('task:cc1') time.sleep(random.randint(1, 3)) print('task3:cc3') time.sleep(random.randint(1, 3)) lock.release() 锁必须有开始和结束,一个acquire必须对应一个release if __name__ == '__main__': p1=Process(target=task1,args=(mutex,)) p2=Process(target=task2,args=(mutex,)) p3=Process(target=task3,args=(mutex,))
p1.start() p2.start() p3.start()
锁可以看作一个运行许可,多个进程同时运行时谁先抢到锁谁才可以运行,没抢到锁的只能等下次