0

Often as I have been browsing this Q & A site, the answers that use multi-threading and processing have told me to use a format that goes like this:

(target=foo, args=(bar, baz))

It is most often used in multiprocessing and multithreading (at least with my limited knowledge.)

My question is, what does target mean, and can someone explain how it is used?

I have not been able to find a good explanation in the docs or elsewhere.

Community
  • 1
  • 1
xxmbabanexx
  • 8,256
  • 16
  • 40
  • 60

2 Answers2

5

The keyword argument target in threading.Thread's constructor sets the entry-point of your new thread. This can be a function or an object which has a __call__ method.

Here's an example using a function:

import threading

def foo(number, name):
    print 'Hello from new thread'
    print 'Here are some arguments:', number, name

thread = threading.Thread(target=foo, args=(5,'bar'))
thread.start()

thread.join()
  • You could improve this answer by showing how arguments are passed. – detly Apr 05 '13 at 05:36
  • `join` waits for the thread to finish executing. While not important in this example, it would have been required if `foo` was taking long to execute. –  Apr 19 '13 at 08:14
0

target is just the callable to invoke in the new thread/process.

From the threading documentation:

target is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called.

nneonneo
  • 171,345
  • 36
  • 312
  • 383