本帖最后由 萌新与小白 于 2020-11-28 14:51 编辑
用锁,创建进程时args里必须传lock,而创建线程时args传不传lock都不报错,这是为什么?
1楼提醒我发错区了,麻烦版主帮忙移下,感谢二位。@苏紫方璇 @苏紫方璇 不知道at成功没
[Python] 纯文本查看 复制代码 # 创建进程时args不传lock,报错,传不报错
import multiprocessing
import os
import time
def run():
lock.acquire()
try:
print(f'子进程 {os.getpid()}')
time.sleep(1)
finally:
lock.release()
if __name__=='__main__':
print(f'主进程 {os.getpid()}')
lock=multiprocessing.Lock()
process_list=[]
for i in range(10):
sub_process=multiprocessing.Process(target=run)
sub_process.start()
process_list.append(sub_process)
for j in process_list:
j.join()
[Python] 纯文本查看 复制代码 # 创建线程时args传不传lock都不报错
import threading
money = 250
def run(n,lock):
global money
for i in range(100000):
lock.acquire()
try:
money = money + n
money = money - n
finally:
lock.release()
if __name__ == '__main__':
lock = threading.Lock()
while True:
t1 = threading.Thread(target=run, args=(10,lock))
t2 = threading.Thread(target=run, args=(15,lock))
t1.start()
t2.start()
t1.join()
t2.join()
if money != 250:
break
print(money) |