【发布时间】:2015-08-03 13:49:30
【问题描述】:
为什么这段代码有效:
data = local()
def main():
proc = multiprocessing.Process(target = foo)
proc.start()
def foo():
data.stuff = 'happiness'
bar()
def bar():
print data.stuff
但是这段代码不起作用?
def main():
proc = multiprocessing.Process(target = foo)
proc.start()
def foo():
local().stuff = 'happiness'
bar()
def bar():
print local().stuff
我们将代码分为几个模块,并且它有多个线程。我们需要将值传递给需要存在于所有这些模块中的线程。
例如:
我们实例化一个工作包。
# inside module_name_a.py
work = Work(a, b, c)
proc = multiprocessing.Process(target = work.do_this)
proc.start()
我们正在做这项工作,我们需要在线程中全局存储一些数据。我们无法更改 Detail 的 API。
# inside work_module_b.py
class Work():
.
.
.
def do_this():
detail = Detail(x, y, z)
local().stuff = 'important'
detail.handle_this()
我们需要handle_this() 的主体来“查看”threading.local() 中的值
# inside detail_module_b.py
class Detail():
.
.
.
def do_this():
detail = Detail(x, y, z)
local().stuff = 'important'
detail.handle_this()
关于正确使用 threading.local() 的任何建议?
【问题讨论】:
-
您使用的是标准 C Python 吗?如果是这样,您的标题可能会产生误导,因为 C Python 并不真正执行多线程。
-
@Tyler 修复了标签和标题
-
使用
threading.Thread而不是multiprocessing.Process。 documentation 状态multiprocessing contains no analogues of [...] threading.local. -
@Vincent 谢谢。如何结束问题?
-
这个帖子解释的很好:stackoverflow.com/questions/1408171/…
标签: python global-variables multiprocessing