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
Barbara StreisandOriginal
2024-11-12 17:58:02973browse

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")

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!

Statement:
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