在下面的代码中,我创建了一个multiprocessing.Array,并将其传递给2个不同的对象,其中一个对象将为此添加1个并保持跟踪no 加一次的次数,另一个加1,并且类似地记下从中减去1的次数。
import multiprocessing
class One(multiprocessing.Process):
def __init__(self, value):
multiprocessing.Process.__init__(self)
def run(self):
run = 0
while True:
with multiprocessing.Lock():
value[0] += -1
run += 1
print(value[0],"subracting -1", run)
class Two(multiprocessing.Process):
def __init__(self, value):
multiprocessing.Process.__init__(self)
def run(self):
run = 0
while True:
with multiprocessing.Lock():
value[0] += 1
run += 1
print(value[0], "adding +1", run)
if __name__=='__main__':
import os
value = multiprocessing.Array('i', 1)
value[0] = 0
os.system("clear")
one = One(value):
two = Two(value)
one.start()
two.start()
two.join()
one.join()
print("Done")
,执行结果为: -221加+1 6953 -220加+1 6954 -221减法-1 7231 -222练习-1 7232 -221加+1 6955 -222修炼-1 7233 -221加+1 6956 -222练习-1 7234 减去1的函数对7324运行,加上1的函数对6956运行,因此结果应为6956-7234 = -278,但是 结果是-222,为什么不是-278?