python创建多进程

python创建多个子进程,各进程间同步

import os
import threading
import time
import multiprocessing
def worker(pro_name,lock):
	print "%s acquiring lock............waiting" %pro_name
        lock.acquire()
	print "%s acquire lock............ok,pid=%d"%(pro_name,os.getpid())
	print "handling......................[%s]"%pro_name
	time.sleep(5)
        lock.release()
	print "%s release lock............ok"%pro_name
processes=[]
lock=multiprocessing.Lock()
for i in range(5):
	process_name="process%d"%i
	process=multiprocessing.Process(target=worker,args=(process_name,lock))
	process.start()
	processes.append(process)
for process in processes:
	process.join()


结果:

process1 acquiring lock............waiting
process0 acquiring lock............waiting
process0 acquire lock............ok,pid=6386
handling......................[process0]
process3 acquiring lock............waiting
process4 acquiring lock............waiting
process2 acquiring lock............waiting
process0 release lock............ok
process1 acquire lock............ok,pid=6387
handling......................[process1]
process1 release lock............ok
process4 acquire lock............ok,pid=6390
handling......................[process4]
process4 release lock............ok
process3 acquire lock............ok,pid=6389
handling......................[process3]
process3 release lock............ok
process2 acquire lock............ok,pid=6388
handling......................[process2]
process2 release lock............ok




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值