Home >Backend Development >Python Tutorial >Why Does My Thread Run Before Calling `Thread.start()` in Python?
Thread Starts Running Before Calling Thread.start
In Python, threading allows for the creation and execution of multiple threads within a single program. A common misconception is that threads start running immediately after being created, even without explicitly calling Thread.start(). However, this is not the case.
Consider the following code snippet:
In this example, two threads t1 and t2 are created but neither of them is started yet. The self.read() function runs indefinitely, which means the program will never reach the print line. This behavior occurs despite not calling t1.start(), which would be expected to start the thread and then proceed to the next line.
The reason for this unexpected behavior lies in the trailing parentheses after target=self.read(). This syntax actually calls the self.read() function immediately and passes the return value as the target argument to the Thread constructor. As Python expects a function to be passed as the target, the solution is to remove the trailing parentheses and explicitly call t1.start() to start the thread:
Alternatively, if the target function requires arguments, you can use the args and kwargs arguments to threading.Thread or define a lambda function to pass to the constructor. Remember that if you choose to use a lambda, it will look up the function and its arguments when the thread is scheduled, not when the lambda is defined. This can lead to unexpected results if you reassign any of the variables before the thread starts running.
The above is the detailed content of Why Does My Thread Run Before Calling `Thread.start()` in Python?. For more information, please follow other related articles on the PHP Chinese website!