The documentation for threading.Thread(target=...)
states that
target
is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called.
I usually use it like this:
import threading
def worker():
a = 3
print("bonjour {a}".format(a=a))
threading.Thread(target=worker).start()
Is there a way to chain the function elements in target
so that a new one does not need to be defined? Something like (pseudocode obviously)
threading.Thread(target=(a=3;print("bonjour {a}".format(a=a))).start()
I have a bunch of very short calls to make in the Thread
call and would like to avoid multiplication of function definitions.
Yes, but you should take care that the function does not alter state in such a way that other threads would be impacted negatively.
I believe it refers to the practice of creating an anonymous class extending Thread and calling its start method in the same line of code.
An inline function is one for which the compiler copies the code from the function definition directly into the code of the calling function rather than creating a separate set of instructions in memory. This eliminates call-linkage overhead and can expose significant optimization opportunities.
There is nothing wrong in calling same function from different threads. If you want to ensure that your variables are consistent it is advisable to provide thread synchronization mechanisms to prevent crashes, racearound conditions.
You can use a lambda function in Python 3.x
import threading
threading.Thread(target=lambda a: print("Hello, {}".format(a)), args=(["world"]))
You should probably take a look at this SO question to see why you can't use print
in Python 2.x in lambda expressions.
Actually, you can fit many function calls into your lambda
:
from __future__ import print_function # I'm on Python 2.7
from threading import Thread
Thread(target=(lambda: print('test') == print('hello'))).start()
That will print both test
and hello
.
I don't really like using exec
, but in Python3.x it is a function, so you could do
threading.Thread(target=exec, args=('a=3; print("bonjour {a}".format(a=a))',)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With