进程锁和线程锁的问题
本帖最后由 萌新与小白 于 2020-11-28 14:51 编辑用锁,创建进程时args里必须传lock,而创建线程时args传不传lock都不报错,这是为什么?
1楼提醒我发错区了,麻烦版主帮忙移下,感谢二位。@苏紫方璇 @苏紫方璇 不知道at成功没
# 创建进程时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()
# 创建线程时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) 枫子树 发表于 2020-11-27 23:45
兄弟发错版块了到讨论求助区
我好像没at成功,怎么at? 枫子树 发表于 2020-11-28 15:18
回帖输入文字上方有@按钮
我编辑时是这么做的,我以为at成功后名字会变蓝,但没变,所以不知道成功没,现在已经移了
页:
[1]