Python之Process(二)
实例:
#!/usr/bin/env python # -*- coding:utf8 -*- # @Time : 2017/12/11 17:12 # @Author : hantong # @File : process_3.py import multiprocessing # lock = multiprocessing.Lock() # lock.acquire() 获取锁 # lock.release() 释放锁 #with lock: #不加锁程序 #number +1 #number +3 import time def add(number,value,lock): with lock: print("init add{0} number = {1}".format(value,number)) for i in xrange(1,5): number += value time.sleep(value) print("add{0} number = {1}".format(value,number)) if __name__ == "__main__": lock = multiprocessing.Lock() number = 0 p1 = multiprocessing.Process(target=add,args=(number,1,lock)) p2 = multiprocessing.Process(target=add,args=(number,3,lock)) p1.start() p2.start() print("main end")执行结果:
main end
init add1 number = 0
add1 number = 1
add1 number = 2
add1 number = 3
add1 number = 4
init add3 number = 0
add3 number = 3
add3 number = 6
add3 number = 9
add3 number = 12