Is print thread safe?

INADA Naoki songofacandy at gmail.com
Mon Aug 11 06:19:05 EDT 2014


On Python 3, print is thread safe.

But Python 2 has broken scenario:

print "spam", "spam", "spam"  # thread 1
print "eggs", "eggs", "eggs"  # thread 2

In this case, 2 lines are mixed.

In your case, "spam spam spam" and "eggs eggs eggs" are not mixed.
But newline is mixed like:

spam spam spameggs eggs eggs

eggs eggs eggsspam spam spam
eggs eggs eggs

spam spam spam


On Mon, Aug 11, 2014 at 4:44 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> Specifically for Python 2.6 and 2.7, but answers for 3.x appreciated as
> well.
>
> Is print thread safe? That is, if I have two threads that each call
> print, say:
>
> print "spam spam spam"  # thread 1
> print "eggs eggs eggs"  # thread 2
>
> I don't care which line prints first, but I do care if the two lines are
> mixed in together, something like this:
>
> spam spaeggs eggs m seggspams
>
>
> Does print perform its own locking to prevent this?
>
>
>
> --
> Steven
> --
> https://mail.python.org/mailman/listinfo/python-list



-- 
INADA Naoki  <songofacandy at gmail.com>



More information about the Python-list mailing list