Thread Premature Execution Without Calling Start
In Python, creating a thread object does not automatically start its execution. However, it is possible for a thread to appear to start running even before the start() method is called. This behavior can be attributed to improper thread creation and is explained below.
Consider the following code snippet:
t1 = threading.Thread(target=self.read) print("something") t2 = threading.Thread(target=self.runChecks(), args=(self,))
In this example, the self.read function is intended to run indefinitely, preventing the program from reaching the subsequent print statement. However, the program skips the print statement altogether. This behavior seems anomalous, as calling start() on a thread typically allows its execution to begin and proceed linearly.
The explanation for this issue lies in the syntax used for creating the thread. In the first line, the parentheses after self.read effectively invoke the function and assign its return value as the target for the thread. This means that self.read is actually running in the main thread, not the newly created thread.
To remedy this, simply remove the parentheses from the target argument:
t1 = threading.Thread(target=self.read) t1.start() print("something")
This ensures that self.read becomes the target function to be run by the thread, and only begins execution after t1.start() is called.
For targets that require arguments, use the args or kwargs parameters of threading.Thread or employ a lambda expression. For instance:
thread = threading.Thread(target=lambda: f(a, b, x=c))
This syntax passes the function and its arguments to the thread, ensuring proper execution.
Remember that lambda functions evaluate their arguments when used, not when defined. This means that redefining variables before scheduling the thread may lead to unexpected results.
The above is the detailed content of Why Does My Thread Run Before Calling `start()` in Python?. For more information, please follow other related articles on the PHP Chinese website!