What makes Python3's print function thread safe?

瘦欲@ 提交于 2020-06-25 11:00:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!