多处理中价值的解释? (意外输出)
explanation of value in multiprocessing? (unexpected output)
我这里有这段代码:
from multiprocessing import Value, Process
def func(x):
x.value += 1
print("child process - " + str(x.value))
x = Value("i")
x.value = 0
print("main process - " + str(x.value))
if __name__ == "__main__":
p1 = Process(target=func, args=(x, ))
p1.start()
p1.join()
p1.close()
print("end - " + str(x.value))
现在,我希望这段代码的输出是:
main process - 0
child process - 1
end - 1
但我得到的是:
main process - 0
main process - 0
end - 0
child process - 1
end - 1
谁能给我解释一下?我是多处理的新手,所以我可能做错了什么。
此致
我可以确认 Joran Beasley 建议的解决方案有效。
当您将所有内容都放在 if __name__ == "__main__"
下时,它会正常工作
我这里有这段代码:
from multiprocessing import Value, Process
def func(x):
x.value += 1
print("child process - " + str(x.value))
x = Value("i")
x.value = 0
print("main process - " + str(x.value))
if __name__ == "__main__":
p1 = Process(target=func, args=(x, ))
p1.start()
p1.join()
p1.close()
print("end - " + str(x.value))
现在,我希望这段代码的输出是:
main process - 0
child process - 1
end - 1
但我得到的是:
main process - 0
main process - 0
end - 0
child process - 1
end - 1
谁能给我解释一下?我是多处理的新手,所以我可能做错了什么。 此致
我可以确认 Joran Beasley 建议的解决方案有效。
当您将所有内容都放在 if __name__ == "__main__"
下时,它会正常工作