2

Why does this code work:

data = local()

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

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

def bar():
  print data.stuff

But this code does not work?

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

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

def bar():
  print local().stuff

We have code divided to several modules and it has multiple threads. We need to pass values to the threads that need to presist in all those modules.

For instance:

We instantiate a parcel of work.

# inside module_name_a.py 
work = Work(a, b, c)
proc = multiprocessing.Process(target = work.do_this)
proc.start()

We are doing this work and we need to store some data globally in the thread. We can't change the API of Detail.

# inside work_module_b.py 
class Work():
  .
  .
  .
  def do_this():
    detail = Detail(x, y, z)
    local().stuff = 'important'
    detail.handle_this()

We need the body of handle_this() to "see" the values inside threading.local()

# inside detail_module_b.py 
class Detail():
  .
  .
  .
  def do_this():
    detail = Detail(x, y, z)
    local().stuff = 'important'
    detail.handle_this()

Any advice about proper use of threading.local() ?

AturSams
  • 7,568
  • 18
  • 64
  • 98
  • Are you using standard C Python? If so, your title might be misleading since C Python doesn't really do multithreading. – T.D. Smith Aug 03 '15 at 13:52
  • @Tyler fixed the tag and title – AturSams Aug 03 '15 at 13:53
  • Use `threading.Thread` instead of `multiprocessing.Process`. The [documentation](https://docs.python.org/2/library/multiprocessing.html#miscellaneous) states `multiprocessing contains no analogues of [...] threading.local.` – Vincent Aug 03 '15 at 13:55
  • @Vincent Thanks. How do you close a question? – AturSams Aug 03 '15 at 13:56
  • This post explain it well: http://stackoverflow.com/questions/1408171/thread-local-storage-in-python – Anatoly Libman Aug 03 '15 at 14:05
  • It all makes sense, there is no point for threading local when with different processes you just have different globals anyway. – AturSams Aug 03 '15 at 14:24

1 Answers1

2

Each time you call local() you get a new thread-local instance. If you call it twice, you've got two different local objects.

It's like doing

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

Your example calls local twice, so you're dealing with two different objects.

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

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

def bar():
  print local().stuff

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

T.D. Smith
  • 984
  • 2
  • 7
  • 22