串行和互斥锁

在多进程时,为了达到一个进程执行完再进行另外一个进程时,如果人为把子进程按先后顺序执行,显然不合理。
#----------------
#     #应该抢资源,先抢到的先锁直到执行完开锁。执行进程的关键就在于这把锁。
# 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()
#------------------------------
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值