If print s
is replaced by print >>sys.stderr, s
then the effect vanishes.
import random, sys, time
import threading
lock = t
Take a look at this stackoverflow thread: How do I get a thread safe print in Python 2.6?. Apparently, printing to sout is not thread-safe.
If you turn on verbose threading, you can see this better:
threading.Thread(target=echo, args=(c,), verbose=True).start()
I get output like this:
MainThread: .start(): starting thread
Thread-1: .__bootstrap(): thread started
MainThread: .start(): starting thread
Thread-2: .__bootstrap(): thread started
MainThread: .start(): starting thread
Thread-3: .__bootstrap(): thread started
MainThread: .join(): waiting until thread stops
a
b
Thread-1: .__bootstrap(): normal return
Thread-2: .__bootstrap(): normal return
MainThread: .join(): thread stopped
MainThread: .join(): waiting until thread stops
Thread-3: .__bootstrap(): normal return
MainThread: .join(): thread stopped
c
You can see that thread 3 is shown as finishing before printing the 'c' character. This clearly cannot be the case, so this leads me to assume that printing to the console is not thread-safe.
This, however, does not explain why printing to sys.stderr appears to work correctly.