互斥锁
互斥锁保证每个进程内的“任务”都会执行完,再执行其他进程,保证了数据的一致性,但降低了效率
from multiprocessing import Process,Lock import time def task(name,mutex): mutex.acquire() print('%s start'%name) time.sleep(1) print('%s end'%name) mutex.release() if __name__ == '__main__': mutex = Lock() p1 = Process(target=task,args=(1,mutex)) p2 = Process(target=task,args=(2,mutex)) p3 = Process(target=task,args=(3,mutex)) p1.start() p2.start() p3.start() p1.join() p2.join() p3.join() print('main')
#1 start
#1 end
#2 start
#2 end
#3 start
#3 end
#main
posted on 2021-01-05 21:15 Hello_Thanos 阅读(77) 评论(0) 编辑 收藏 举报