Thread Execution Prematurely Initiated
Despite not having invoked t1.start(), why does t1 commence execution before the subsequent print statement?
Analysis
The presence of parentheses after self.read() in t1's target definition triggers premature execution due to Python's default parameter passing semantics. By omitting the parentheses, self.read is passed as a function reference rather than the result of executing it.
Resolution
To ensure correct execution, remove the trailing parentheses from self.read():
# Remove parentheses to pass a function reference t1 = threading.Thread(target=self.read) t1.start() print("something")
For targets requiring arguments, use args and kwargs or a lambda function:
# Using args and kwargs (preferred) t1 = threading.Thread(target=f, args=(a, b), kwargs={'x': c}) # Using a lambda function (watch for variable reassignment issues) t1 = threading.Thread(target=lambda: f(a, b, x=c))
The above is the detailed content of Why Does My Thread Execute Before the Print Statement?. For more information, please follow other related articles on the PHP Chinese website!