问题
I've seen on various mailing lists and forums that people keep mentioning that the print function in Python 3 is thread safe. From my own testing, I see no reason to doubt that.
import threading
import time
import random
def worker(letter):
print(letter * 50)
threads = [threading.Thread(target=worker, args=(let,)) for let in "ABCDEFGHIJ"]
for t in threads:
t.start()
for t in threads:
t.join()
When I run it with Python 3, even though some of the lines may be out of order, they are still always on their own lines. With Python 2, however, the output is fairly sporadic. Some lines are joined together or indented. This is also the case when I from __future__ import print_function
- Python 2.7 builtin_print <- not thread safe
- Python 3.6 builtin_print <- thread safe?
I'm just trying to understand WHY this is the case?
来源:https://stackoverflow.com/questions/42867866/what-makes-python3s-print-function-thread-safe