Home > Backend Development > Python Tutorial > Why Does My Thread Execute Before the Print Statement?

Why Does My Thread Execute Before the Print Statement?

Barbara Streisand
Release: 2024-11-12 17:58:02
Original
963 people have browsed it

Why Does My Thread Execute Before the Print Statement?

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")
Copy after login

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))
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template