我试图学习python中的并行编程和多处理。我知道锁就像“睡眠”一样,因此它使另一个进程等待,直到当前进程完成该代码块或共享内存为止。但是问题是输出是
import multiprocessing
# function to withdraw from account
def withdraw(balance, lock):
for _ in range(10):
lock.acquire()
print("with")
balance.value = balance.value - 1
lock.release()
# function to deposit to account
def deposit(balance, lock):
for _ in range(10):
lock.acquire()
print("depp")
balance.value = balance.value + 1
lock.release()
def perform_transactions():
# initial balance (in shared memory)
balance = multiprocessing.Value('i', 100)
# creating a lock object
lock = multiprocessing.Lock()
# creating new processes
p1 = multiprocessing.Process(target=withdraw, args=(balance,lock))
p2 = multiprocessing.Process(target=deposit, args=(balance,lock))
# starting processes
p1.start()
p2.start()
# wait until processes are finished
p1.join()
p2.join()
# print final balance
print("Final balance = {}".format(balance.value))
if __name__ == "__main__":
for _ in range(10):
# perform same transaction process 10 times
perform_transactions()
第一个输出:
与 与 与 与 与 与 与 与 与 与 德普 德普 德普 德普 德普 德普 德普 德普 德普 德普 最终余额= 100
我以为它会像“ dep with dep with ... etc”之类,但是它打印dep十次和十次,这意味着它首先执行了整个过程而没有并行性。
如果“ lock.acquire()”在循环之前,而“ lock.release()”在循环之后,则是有意义的。
另一个输出也很奇怪
with
with
with
depp
depp
depp
depp
depp
depp
depp
depp
depp
depp
with
with
with
with
with
with
with
Final balance = 100