Home >Backend Development >Python Tutorial >Why does my Python thread execute before I explicitly start it?
Thread Execution Before Explicit Invocation
Python's multithreading module allows for parallel execution of code using Thread objects. However, an unusual behavior can occur when creating and configuring threads.
The issue arises when passing a function to a Thread's target argument with trailing parentheses, as shown below:
t1 = threading.Thread(target=self.read())
This behavior stems from the misconception that calling target=self.read() will assign the running of self.read() to the thread. Unfortunately, this is incorrect. By appending the parentheses, the function is invoked immediately, and its return value is assigned as the target instead. For a Thread object, it expects to receive a function as the target.
To resolve this issue, simply remove the parentheses from the target argument and explicitly invoke the thread's start() method:
t1 = threading.Thread(target=self.read) t1.start()
Now, self.read() will run indefinitely in the newly created thread, allowing the program to proceed and print "something." This modification ensures that the function is assigned as the target correctly and is not executed prematurely.
The above is the detailed content of Why does my Python thread execute before I explicitly start it?. For more information, please follow other related articles on the PHP Chinese website!