Python多线程未并行执行?为何输出出现连续‘aaabbb’?
The Problem
I ran this Python code to test multi-threading:
from time import sleep from threading import * class myclass1(Thread): def run(self): for i in range(5): print("aaa") sleep(1) class myclass2(Thread): def run(self): for i in range(5): print("bbb") sleep(1) mc1 = myclass1() mc2 = myclass2() mc1.start() mc2.start()
The output I got included the combined string "aaabbb", looking like this:
aaa bbb aaabbb aaa bbb aaa bbb aaa bbb
I don't understand why "aaabbb" shows up—does this mean a single thread is executing print("aaabbb")?
The Explanation
Great question! This isn't because any thread is running print("aaabbb")—it's all about how thread scheduling and the print() function work in Python.
When you start both threads, your operating system switches between them rapidly to give the illusion of simultaneous execution. Here's what's happening:
- The
print()function doesn't write its entire output to the console in one atomic, uninterruptable step. Under the hood, it sends the string to stdout (your console) in chunks, and the OS can pause one thread mid-write to let the other thread run. - So, if
myclass1starts printing "aaa", but the OS switches tomyclass2before all three 'a's are fully written,myclass2will start printing "bbb" right after the partial "aaa"—resulting in "aaabbb" being printed together.
How to Fix It
To prevent this, you need to make the print() calls thread-safe by using a lock. A lock ensures that only one thread can execute the print operation at a time:
from time import sleep from threading import Thread, Lock # Create a shared lock for print operations print_lock = Lock() class myclass1(Thread): def run(self): for i in range(5): # Use the lock to ensure atomic print with print_lock: print("aaa") sleep(1) class myclass2(Thread): def run(self): for i in range(5): with print_lock: print("bbb") sleep(1) mc1 = myclass1() mc2 = myclass2() mc1.start() mc2.start()
With this lock in place, each print() will complete fully before the other thread can write to stdout, so you'll never see combined strings like "aaabbb".
内容的提问来源于stack exchange,提问作者Bob

