0

I would like to run a thread, which will populate a queue on the computation graph from normal python operations. The thread will use sess object, some of tensors and some data.

How to pass data to the thread?

Here is seen some sample: https://stackoverflow.com/a/34596212/258483

load_and_enqueue function should be ran in a separate thread. It is started with

t = threading.Thread(target=load_and_enqueue)
t.start()

but how sess and enqueue_op reach inside of a thread? These declared as function parameters, so it is not a closure. So, is this author's error or Python allows this way of sending parameters?

Community
  • 1
  • 1
Dims
  • 47,675
  • 117
  • 331
  • 600

1 Answers1

3

If you have a function load_and_enqueue(foo, bar, baz) and you want to run it in a thread with particular values for the arguments, you can start it with those arguments as follows:

def load_and_enqueue(foo, bar, baz):
  # ...

foo_arg = ...
bar_arg = ...
baz_arg = ...

t = threading.Thread(target=load_and_enqueue, args=(foo_arg, bar_arg, baz_arg))
t.start()

N.B. The original SO answer has been modified because it was intended to simply capture the variables from the enclosing scope.

Community
  • 1
  • 1
mrry
  • 125,488
  • 26
  • 399
  • 400
  • Is it possible to capture values? To capture values, shouldn't I remove variables from argument list? – Dims Feb 03 '16 at 17:28
  • Yes, the thread will capture values defined before the function, so (approximately speaking) if there were variables `foo`, `bar` and `baz` defined before the function, you would not need (i) define them as formal arguments to the function, and (ii) pass them as `args` in the thread constructor. – mrry Feb 03 '16 at 17:31