【问题标题】:How to use threading.local() correctly to pass values?如何正确使用 threading.local() 来传递值?
【发布时间】: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.Processdocumentation 状态 multiprocessing contains no analogues of [...] threading.local.
  • @Vincent 谢谢。如何结束问题?
  • 这个帖子解释的很好:stackoverflow.com/questions/1408171/…

标签: python global-variables multiprocessing


【解决方案1】:

每次调用 local() 都会得到一个新的线程本地实例。如果你调用它两次,你就会得到两个不同的本地对象。

就像在做

new Car().setColor(red)
new Car().getColor()

您的示例调用本地两次,因此您处理的是两个不同的对象。

def main():
  proc = multiprocessing.Process(target = foo)
  proc.start()

def foo():
  local().stuff = 'happiness'
  bar()

def bar():
  print local().stuff

https://docs.python.org/2/library/threading.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-14
    • 2021-12-10
    • 2021-09-16
    • 2012-10-11
    • 2013-03-14
    • 1970-01-01
    相关资源
    最近更新 更多