在多进程时,为了达到一个进程执行完再进行另外一个进程时,如果人为把子进程按先后顺序执行,显然不合理。 #---------------- # #应该抢资源,先抢到的先锁直到执行完开锁。执行进程的关键就在于这把锁。 # from multiprocessing import Process,Lock # import time,random # mutex = Lock() #实例化锁的对象 # #假如这个进程是由word程序打印 # def task1(lock): # lock.acquire() # 上锁 # print(' 任务1 名字是:英格拉姆') # time.sleep(random.randint(1,5)) # print('任务1 性别是:male') # time.sleep(random.randint(1,5)) # print('任务1 年龄是:22') # time.sleep(random.randint(1,5)) # lock.release() #解锁 # #这个进程是由notepad++程序打印 # def task2(lock): # lock.acquire() #上锁 # print('任务2 名字是:卡戴珊') # time.sleep(random.randint(1,5)) # print('任务2 性别是:female') # time.sleep(random.randint(1,5)) # print('任务2 年龄是:25') # time.sleep(random.randint(1,5)) # lock.release() # #这个进程是由wps程序打印 # def task3(lock): # lock.acquire() # print('任务3 名字是:詹姆斯') # time.sleep(random.randint(1,5)) # print('任务3 性别是:male') # time.sleep(random.randint(1,5)) # print('任务3 年龄是:34') # time.sleep(random.randint(1,5)) # lock.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() # #print('主进程') # #------------------------------ # #可以使用锁来确保一次只有一个进程打印到标准输出 # from multiprocessing import Process,Lock # def f(l,i): # l.acquire() # try: # print('hello world',i) # finally: # l.release() # if __name__ == '__main__': # lock =Lock() # for num in range(10): #利用for循环来创建多个子进程 # Process(target=f,args=(lock,num)).start() #------------------------------
串行和互斥锁
最新推荐文章于 2024-07-19 16:36:18 发布